<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/xlrblog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/xlrblog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/xlrblog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/xlrblog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/xlrblog/css/main.css">


<link rel="stylesheet" href="/xlrblog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/xlrblog/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="多级缓存（什么是多级缓存、JVM进程缓存、Lua语法入门、实现多级缓存、缓存同步） 1.什么是多级缓存传统的缓存策略一般是请求到达Tomcat后，先查询Redis，如果未命中则查询数据库，如图：  存在下面的问题： •请求要经过Tomcat处理，Tomcat的性能成为整个系统的瓶颈 •Redis缓存失效时，会对数据库产生冲击 多级缓存就是充分利用请求处理的每个环节，分别添加缓存，减轻Tomcat压">
<meta property="og:type" content="article">
<meta property="og:title" content="多级缓存">
<meta property="og:url" content="https://gitee.com/xlr0306/2023/11/18/%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98/index.html">
<meta property="og:site_name" content="君不见的博客">
<meta property="og:description" content="多级缓存（什么是多级缓存、JVM进程缓存、Lua语法入门、实现多级缓存、缓存同步） 1.什么是多级缓存传统的缓存策略一般是请求到达Tomcat后，先查询Redis，如果未命中则查询数据库，如图：  存在下面的问题： •请求要经过Tomcat处理，Tomcat的性能成为整个系统的瓶颈 •Redis缓存失效时，会对数据库产生冲击 多级缓存就是充分利用请求处理的每个环节，分别添加缓存，减轻Tomcat压">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821075259137.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821075558137.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821080511581.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821080954947.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821081418456.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821081826399.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821091437975.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821091621308.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821091638140.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821091835406.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821091904332.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821092657918.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821092902946.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821092941139.png">
<meta property="og:image" content="https://gitee.com/Spring%20Cloud%E7%AD%89/assets/image-20200310225539214.png">
<meta property="og:image" content="https://gitee.com/Spring%20Cloud%E7%AD%89/assets/image-20210811100653291.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/yeVDlwtfMx.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821093144700.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821094447709.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821100755080.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821100801756.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821101217089.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821101433528.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821101721649.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821102235467.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821102610167.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821102959829.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821104149061.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821104857413.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821110441222.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821111023255.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821112420464.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821112444482.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821112559965.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821112637430.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821113340111.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821114528954.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821114742950.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821115108528.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821115552327.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821115719363.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821115914748.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821115948395.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821120017324.png">
<meta property="og:image" content="https://gitee.com/Spring%20Cloud%E7%AD%89/%E9%AB%98%E7%BA%A7%E7%AF%87/%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99/day04-%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98/%E8%B5%84%E6%96%99/assets/image-20210813153241537.png">
<meta property="og:image" content="https://gitee.com/Spring%20Cloud%E7%AD%89/%E9%AB%98%E7%BA%A7%E7%AF%87/%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99/day04-%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98/%E8%B5%84%E6%96%99/assets/image-20200327094735948.png">
<meta property="og:image" content="https://gitee.com/Spring%20Cloud%E7%AD%89/%E9%AB%98%E7%BA%A7%E7%AF%87/%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99/day04-%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98/%E8%B5%84%E6%96%99/assets/image-20210813161804292.png">
<meta property="og:image" content="https://gitee.com/xlrblog/assets/image-20210821120049024.png">
<meta property="article:published_time" content="2023-11-18T08:12:51.000Z">
<meta property="article:modified_time" content="2023-11-18T08:15:17.496Z">
<meta property="article:author" content="君不见">
<meta property="article:tag" content="SpringCloud">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/xlrblog/assets/image-20210821075259137.png">

<link rel="canonical" href="https://gitee.com/xlr0306/2023/11/18/%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>多级缓存 | 君不见的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/xlrblog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">君不见的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">记录生活中的点点滴滴</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/xlrblog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/xlrblog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/xlrblog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/xlrblog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/xlr0306/2023/11/18/%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/xlrblog/images/avatar.gif">
      <meta itemprop="name" content="君不见">
      <meta itemprop="description" content="君不见，黄河之水天上来，奔流到海不复回。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="君不见的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          多级缓存
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2023-11-18 16:12:51 / 修改时间：16:15:17" itemprop="dateCreated datePublished" datetime="2023-11-18T16:12:51+08:00">2023-11-18</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/xlrblog/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/xlrblog/categories/Java/SpringCloud/" itemprop="url" rel="index"><span itemprop="name">SpringCloud</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>多级缓存（什么是多级缓存、JVM进程缓存、Lua语法入门、实现多级缓存、缓存同步）</p>
<h1 id="1-什么是多级缓存"><a href="#1-什么是多级缓存" class="headerlink" title="1.什么是多级缓存"></a>1.什么是多级缓存</h1><p>传统的缓存策略一般是请求到达Tomcat后，先查询Redis，如果未命中则查询数据库，如图：</p>
<p><img src="/xlrblog/assets/image-20210821075259137.png" alt="image-20210821075259137"></p>
<p>存在下面的问题：</p>
<p>•请求要经过Tomcat处理，Tomcat的性能成为整个系统的瓶颈</p>
<p>•Redis缓存失效时，会对数据库产生冲击</p>
<p>多级缓存就是充分利用请求处理的每个环节，分别添加缓存，减轻Tomcat压力，提升服务性能：</p>
<ul>
<li>浏览器访问静态资源时，优先读取浏览器本地缓存</li>
<li>访问非静态资源（ajax查询数据）时，访问服务端</li>
<li>请求到达Nginx后，优先读取Nginx本地缓存</li>
<li>如果Nginx本地缓存未命中，则去直接查询Redis（不经过Tomcat）</li>
<li>如果Redis查询未命中，则查询Tomcat</li>
<li>请求进入Tomcat后，优先查询JVM进程缓存</li>
<li>如果JVM进程缓存未命中，则查询数据库</li>
</ul>
<p><img src="/xlrblog/assets/image-20210821075558137.png" alt="image-20210821075558137"></p>
<p>在多级缓存架构中，Nginx内部需要编写本地缓存查询、Redis查询、Tomcat查询的业务逻辑，因此这样的nginx服务不再是一个<strong>反向代理服务器</strong>，而是一个编写<strong>业务的Web服务器了</strong>。</p>
<p>因此这样的业务Nginx服务也需要搭建集群来提高并发，再有专门的nginx服务来做反向代理，如图：</p>
<p><img src="/xlrblog/assets/image-20210821080511581.png" alt="image-20210821080511581"></p>
<p>另外，我们的Tomcat服务将来也会部署为集群模式：</p>
<p><img src="/xlrblog/assets/image-20210821080954947.png" alt="image-20210821080954947"></p>
<p>可见，多级缓存的关键有两个：</p>
<ul>
<li><p>一个是在nginx中编写业务，实现nginx本地缓存、Redis、Tomcat的查询</p>
</li>
<li><p>另一个就是在Tomcat中实现JVM进程缓存</p>
</li>
</ul>
<p>其中Nginx编程则会用到OpenResty框架结合Lua这样的语言。</p>
<p>这也是今天课程的难点和重点。</p>
<h1 id="2-JVM进程缓存"><a href="#2-JVM进程缓存" class="headerlink" title="2.JVM进程缓存"></a>2.JVM进程缓存</h1><p>为了演示多级缓存的案例，我们先准备一个商品查询的业务。</p>
<h2 id="2-1-导入案例"><a href="#2-1-导入案例" class="headerlink" title="2.1.导入案例"></a>2.1.导入案例</h2><p>参考课前资料的：《案例导入说明.md》</p>
<p><img src="/xlrblog/assets/image-20210821081418456.png" alt="image-20210821081418456"> </p>
<h2 id="2-2-初识Caffeine"><a href="#2-2-初识Caffeine" class="headerlink" title="2.2.初识Caffeine"></a>2.2.初识Caffeine</h2><p>缓存在日常开发中启动至关重要的作用，由于是存储在内存中，数据的读取速度是非常快的，能大量减少对数据库的访问，减少数据库的压力。我们把缓存分为两类：</p>
<ul>
<li>分布式缓存，例如Redis：<ul>
<li>优点：存储容量更大、可靠性更好、可以在集群间共享</li>
<li>缺点：访问缓存有网络开销</li>
<li>场景：缓存数据量较大、可靠性要求较高、需要在集群间共享</li>
</ul>
</li>
<li>进程本地缓存，例如HashMap、GuavaCache：<ul>
<li>优点：读取本地内存，没有网络开销，速度更快</li>
<li>缺点：存储容量有限、可靠性较低、无法共享</li>
<li>场景：性能要求较高，缓存数据量较小</li>
</ul>
</li>
</ul>
<p>我们今天会利用Caffeine框架来实现JVM进程缓存。</p>
<p><strong>Caffeine</strong>是一个基于Java8开发的，提供了近乎最佳命中率的高性能的本地缓存库。目前Spring内部的缓存使用的就是Caffeine。GitHub地址：<a target="_blank" rel="noopener" href="https://github.com/ben-manes/caffeine">https://github.com/ben-manes/caffeine</a></p>
<p>Caffeine的性能非常好，下图是官方给出的性能对比：</p>
<p><img src="/xlrblog/assets/image-20210821081826399.png" alt="image-20210821081826399"></p>
<p>可以看到Caffeine的性能遥遥领先！</p>
<p>缓存使用的基本API：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">testBasicOps</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="comment">// 构建cache对象</span></span><br><span class="line">    Cache&lt;String, String&gt; cache = Caffeine.newBuilder().build();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 存数据</span></span><br><span class="line">    cache.put(<span class="string">&quot;gf&quot;</span>, <span class="string">&quot;迪丽热巴&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 取数据</span></span><br><span class="line">    <span class="type">String</span> <span class="variable">gf</span> <span class="operator">=</span> cache.getIfPresent(<span class="string">&quot;gf&quot;</span>);</span><br><span class="line">    System.out.println(<span class="string">&quot;gf = &quot;</span> + gf);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 取数据，包含两个参数：</span></span><br><span class="line">    <span class="comment">// 参数一：缓存的key</span></span><br><span class="line">    <span class="comment">// 参数二：Lambda表达式，表达式参数就是缓存的key，方法体是查询数据库的逻辑</span></span><br><span class="line">    <span class="comment">// 优先根据key查询JVM缓存，如果未命中，则执行参数二的Lambda表达式</span></span><br><span class="line">    <span class="type">String</span> <span class="variable">defaultGF</span> <span class="operator">=</span> cache.get(<span class="string">&quot;defaultGF&quot;</span>, key -&gt; &#123;</span><br><span class="line">        <span class="comment">// 根据key去数据库查询数据</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;柳岩&quot;</span>;</span><br><span class="line">    &#125;);</span><br><span class="line">    System.out.println(<span class="string">&quot;defaultGF = &quot;</span> + defaultGF);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<p>Caffeine既然是缓存的一种，肯定需要有缓存的清除策略，不然的话内存总会有耗尽的时候。</p>
<p>Caffeine提供了三种缓存驱逐策略：</p>
<ul>
<li><p><strong>基于容量</strong>：设置缓存的数量上限</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建缓存对象</span></span><br><span class="line">Cache&lt;String, String&gt; cache = Caffeine.newBuilder()</span><br><span class="line">    .maximumSize(<span class="number">1</span>) <span class="comment">// 设置缓存大小上限为 1</span></span><br><span class="line">    .build();</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>基于时间</strong>：设置缓存的有效时间</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建缓存对象</span></span><br><span class="line">Cache&lt;String, String&gt; cache = Caffeine.newBuilder()</span><br><span class="line">    <span class="comment">// 设置缓存有效期为 10 秒，从最后一次写入开始计时 </span></span><br><span class="line">    .expireAfterWrite(Duration.ofSeconds(<span class="number">10</span>)) </span><br><span class="line">    .build();</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>基于引用</strong>：设置缓存为软引用或弱引用，利用GC来回收缓存数据。性能较差，不建议使用。</p>
</li>
</ul>
<blockquote>
<p><strong>注意</strong>：在默认情况下，当一个缓存元素过期的时候，Caffeine不会自动立即将其清理和驱逐。而是在一次读或写操作后，或者在空闲时间完成对失效数据的驱逐。</p>
</blockquote>
<h2 id="2-3-实现JVM进程缓存"><a href="#2-3-实现JVM进程缓存" class="headerlink" title="2.3.实现JVM进程缓存"></a>2.3.实现JVM进程缓存</h2><h3 id="2-3-1-需求"><a href="#2-3-1-需求" class="headerlink" title="2.3.1.需求"></a>2.3.1.需求</h3><p>利用Caffeine实现下列需求：</p>
<ul>
<li>给根据id查询商品的业务添加缓存，缓存未命中时查询数据库</li>
<li>给根据id查询商品库存的业务添加缓存，缓存未命中时查询数据库</li>
<li>缓存初始大小为100</li>
<li>缓存上限为10000</li>
</ul>
<h3 id="2-3-2-实现"><a href="#2-3-2-实现" class="headerlink" title="2.3.2.实现"></a>2.3.2.实现</h3><p>首先，我们需要定义两个Caffeine的缓存对象，分别保存商品、库存的缓存数据。</p>
<p>在item-service的<code>com.heima.item.config</code>包下定义<code>CaffeineConfig</code>类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.heima.item.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.github.benmanes.caffeine.cache.Cache;</span><br><span class="line"><span class="keyword">import</span> com.github.benmanes.caffeine.cache.Caffeine;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.pojo.Item;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.pojo.ItemStock;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CaffeineConfig</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Cache&lt;Long, Item&gt; <span class="title function_">itemCache</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Caffeine.newBuilder()</span><br><span class="line">                .initialCapacity(<span class="number">100</span>)</span><br><span class="line">                .maximumSize(<span class="number">10_000</span>)</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Cache&lt;Long, ItemStock&gt; <span class="title function_">stockCache</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Caffeine.newBuilder()</span><br><span class="line">                .initialCapacity(<span class="number">100</span>)</span><br><span class="line">                .maximumSize(<span class="number">10_000</span>)</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>然后，修改item-service中的<code>com.heima.item.web</code>包下的ItemController类，添加缓存逻辑：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;item&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ItemController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> IItemService itemService;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> IItemStockService stockService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> Cache&lt;Long, Item&gt; itemCache;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> Cache&lt;Long, ItemStock&gt; stockCache;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// ...其它略</span></span><br><span class="line">    </span><br><span class="line">    <span class="meta">@GetMapping(&quot;/&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Item <span class="title function_">findById</span><span class="params">(<span class="meta">@PathVariable(&quot;id&quot;)</span> Long id)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> itemCache.get(id, key -&gt; itemService.query()</span><br><span class="line">                .ne(<span class="string">&quot;status&quot;</span>, <span class="number">3</span>).eq(<span class="string">&quot;id&quot;</span>, key)</span><br><span class="line">                .one()</span><br><span class="line">        );</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/stock/&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> ItemStock <span class="title function_">findStockById</span><span class="params">(<span class="meta">@PathVariable(&quot;id&quot;)</span> Long id)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> stockCache.get(id, key -&gt; stockService.getById(key));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h1 id="3-Lua语法入门"><a href="#3-Lua语法入门" class="headerlink" title="3.Lua语法入门"></a>3.Lua语法入门</h1><p>Nginx编程需要用到Lua语言，因此我们必须先入门Lua的基本语法。</p>
<h2 id="3-1-初识Lua"><a href="#3-1-初识Lua" class="headerlink" title="3.1.初识Lua"></a>3.1.初识Lua</h2><p>Lua 是一种轻量小巧的脚本语言，用标准C语言编写并以源代码形式开放， 其设计目的是为了嵌入应用程序中，从而为应用程序提供灵活的扩展和定制功能。官网：<a target="_blank" rel="noopener" href="https://www.lua.org/">https://www.lua.org/</a></p>
<p><img src="/xlrblog/assets/image-20210821091437975.png" alt="image-20210821091437975"></p>
<p>Lua经常嵌入到C语言开发的程序中，例如游戏开发、游戏插件等。</p>
<p>Nginx本身也是C语言开发，因此也允许基于Lua做拓展。</p>
<h2 id="3-1-HelloWorld"><a href="#3-1-HelloWorld" class="headerlink" title="3.1.HelloWorld"></a>3.1.HelloWorld</h2><p>CentOS7默认已经安装了Lua语言环境，所以可以直接运行Lua代码。</p>
<p>1）在Linux虚拟机的任意目录下，新建一个hello.lua文件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">touch hello.lua</span><br></pre></td></tr></table></figure>

<p><img src="/xlrblog/assets/image-20210821091621308.png" alt="image-20210821091621308"></p>
<p>2）添加下面的内容</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(<span class="string">&quot;Hello World!&quot;</span>)  </span><br></pre></td></tr></table></figure>



<p>3）运行</p>
<p><img src="/xlrblog/assets/image-20210821091638140.png" alt="image-20210821091638140"></p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">root@iZf8zejhe9y0gfgh05lo35Z:/tmp# lua hello.lua</span><br><span class="line">Hello World!</span><br></pre></td></tr></table></figure>



<h2 id="3-2-变量和循环"><a href="#3-2-变量和循环" class="headerlink" title="3.2.变量和循环"></a>3.2.变量和循环</h2><p>学习任何语言必然离不开变量，而变量的声明必须先知道数据的类型。</p>
<h3 id="3-2-1-Lua的数据类型"><a href="#3-2-1-Lua的数据类型" class="headerlink" title="3.2.1.Lua的数据类型"></a>3.2.1.Lua的数据类型</h3><p>Lua中支持的常见数据类型包括：</p>
<p><img src="/xlrblog/assets/image-20210821091835406.png" alt="image-20210821091835406"></p>
<table>
<thead>
<tr>
<th>数据类型</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>nil</td>
<td>这个最简单，只有值nil属于该类，表示一个无效值（在条件表达式中相当于false）。</td>
</tr>
<tr>
<td>boolean</td>
<td>包含两个值：false和true</td>
</tr>
<tr>
<td>number</td>
<td>表示双精度类型的实浮点数</td>
</tr>
<tr>
<td>string</td>
<td>字符串由一对双引号或单引号来表示</td>
</tr>
<tr>
<td>function</td>
<td>由 C   或 Lua   编写的函数</td>
</tr>
<tr>
<td>table</td>
<td>Lua 中的表（table）其实是一个”关联数组”（associative arrays），数组的索引可以是数字、字符串或表类型。在   Lua   里，table   的创建是通过”构造表达式”来完成，最简单构造表达式是{}，用来创建一个空表。</td>
</tr>
</tbody></table>
<p>另外，Lua提供了type()函数来判断一个变量的数据类型：</p>
<p><img src="/xlrblog/assets/image-20210821091904332.png" alt="image-20210821091904332"></p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">root@iZf8zejhe9y0gfgh05lo35Z:/tmp# lua</span><br><span class="line">Lua <span class="number">5.4</span><span class="number">.4</span>  Copyright (C) <span class="number">1994</span><span class="number">-2022</span> Lua.org, PUC-Rio</span><br><span class="line">&gt; <span class="built_in">print</span>(<span class="built_in">type</span>(<span class="string">&quot;Hello&quot;</span>))</span><br><span class="line"><span class="built_in">string</span></span><br><span class="line">&gt; <span class="built_in">print</span>(<span class="built_in">type</span>(<span class="number">10.5</span>*<span class="number">6</span>))</span><br><span class="line">number</span><br><span class="line">&gt; </span><br></pre></td></tr></table></figure>

<h3 id="3-2-2-声明变量"><a href="#3-2-2-声明变量" class="headerlink" title="3.2.2.声明变量"></a>3.2.2.声明变量</h3><p>Lua声明变量的时候无需指定数据类型，而是用<strong>local来声明变量为局部变量</strong>：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 声明字符串，可以用单引号或双引号，</span></span><br><span class="line"><span class="keyword">local</span> str = <span class="string">&#x27;hello&#x27;</span></span><br><span class="line"><span class="comment">-- 字符串拼接可以使用 ..</span></span><br><span class="line"><span class="keyword">local</span> str2 = <span class="string">&#x27;hello&#x27;</span> .. <span class="string">&#x27;world&#x27;</span></span><br><span class="line"><span class="comment">-- 声明数字</span></span><br><span class="line"><span class="keyword">local</span> num = <span class="number">21</span></span><br><span class="line"><span class="comment">-- 声明布尔类型</span></span><br><span class="line"><span class="keyword">local</span> flag = <span class="literal">true</span></span><br></pre></td></tr></table></figure>



<p>Lua中的table类型既可以作为数组，又可以作为Java中的map来使用。数组就是特殊的table，key是数组角标而已：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 声明数组 ，key为角标的 table</span></span><br><span class="line"><span class="keyword">local</span> arr = &#123;<span class="string">&#x27;java&#x27;</span>, <span class="string">&#x27;python&#x27;</span>, <span class="string">&#x27;lua&#x27;</span>&#125;</span><br><span class="line"><span class="comment">-- 声明table，类似java的map</span></span><br><span class="line"><span class="keyword">local</span> map =  &#123;name=<span class="string">&#x27;Jack&#x27;</span>, age=<span class="number">21</span>&#125;</span><br></pre></td></tr></table></figure>

<p>Lua中的数组角标是从1开始，访问的时候与Java中类似：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 访问数组，lua数组的角标从1开始</span></span><br><span class="line"><span class="built_in">print</span>(arr[<span class="number">1</span>])</span><br></pre></td></tr></table></figure>

<p>Lua中的table可以用key来访问：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 访问table</span></span><br><span class="line"><span class="built_in">print</span>(map[<span class="string">&#x27;name&#x27;</span>])</span><br><span class="line"><span class="built_in">print</span>(map.name)</span><br></pre></td></tr></table></figure>



<h3 id="3-2-3-循环"><a href="#3-2-3-循环" class="headerlink" title="3.2.3.循环"></a>3.2.3.循环</h3><p>对于table，我们可以利用for循环来遍历。不过数组和普通table遍历略有差异。</p>
<p>遍历数组：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 声明数组 key为索引的 table</span></span><br><span class="line">arr = &#123;<span class="string">&#x27;java&#x27;</span>, <span class="string">&#x27;python&#x27;</span>, <span class="string">&#x27;lua&#x27;</span>&#125;</span><br><span class="line"><span class="comment">-- 遍历数组</span></span><br><span class="line"><span class="keyword">for</span> index,value <span class="keyword">in</span> <span class="built_in">ipairs</span>(arr) <span class="keyword">do</span></span><br><span class="line">    <span class="built_in">print</span>(index, value) </span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>

<p>遍历普通table</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 声明map，也就是table</span></span><br><span class="line">map = &#123;name=<span class="string">&#x27;Jack&#x27;</span>, age=<span class="number">21</span>&#125;</span><br><span class="line"><span class="comment">-- 遍历table</span></span><br><span class="line"><span class="keyword">for</span> key,value <span class="keyword">in</span> <span class="built_in">pairs</span>(map) <span class="keyword">do</span></span><br><span class="line">   <span class="built_in">print</span>(key, value) </span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>







<h2 id="3-3-条件控制、函数"><a href="#3-3-条件控制、函数" class="headerlink" title="3.3.条件控制、函数"></a>3.3.条件控制、函数</h2><p>Lua中的条件控制和函数声明与Java类似。</p>
<h3 id="3-3-1-函数"><a href="#3-3-1-函数" class="headerlink" title="3.3.1.函数"></a>3.3.1.函数</h3><p>定义函数的语法：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> 函数名<span class="params">( argument1, argument2..., argumentn)</span></span></span><br><span class="line">    <span class="comment">-- 函数体</span></span><br><span class="line">    <span class="keyword">return</span> 返回值</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>



<p>例如，定义一个函数，用来打印数组：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printArr</span><span class="params">(arr)</span></span></span><br><span class="line">    <span class="keyword">for</span> index, value <span class="keyword">in</span> <span class="built_in">ipairs</span>(arr) <span class="keyword">do</span></span><br><span class="line">        <span class="built_in">print</span>(value)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>



<h3 id="3-3-2-条件控制"><a href="#3-3-2-条件控制" class="headerlink" title="3.3.2.条件控制"></a>3.3.2.条件控制</h3><p>类似Java的条件控制，例如if、else语法：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(布尔表达式)</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="comment">--[ 布尔表达式为 true 时执行该语句块 --]</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="comment">--[ 布尔表达式为 false 时执行该语句块 --]</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>与java不同，布尔表达式中的逻辑运算是基于英文单词：</p>
<table>
<thead>
<tr>
<th>操作符</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody><tr>
<td>and</td>
<td>逻辑与操作符。   若 A 为   false，则返回   A，否则返回   B。</td>
<td>(A and B) 为   false。</td>
</tr>
<tr>
<td>or</td>
<td>逻辑或操作符。   若 A 为   true，则返回   A，否则返回   B。</td>
<td>(A or B) 为   true。</td>
</tr>
<tr>
<td>not</td>
<td>逻辑非操作符。与逻辑运算结果相反，如果条件为   true，逻辑非为   false。</td>
<td>not(A and B) 为   true。</td>
</tr>
</tbody></table>
<p><img src="/xlrblog/assets/image-20210821092657918.png" alt="image-20210821092657918"></p>
<h3 id="3-3-3-案例"><a href="#3-3-3-案例" class="headerlink" title="3.3.3.案例"></a>3.3.3.案例</h3><p>需求：自定义一个函数，可以打印table，当参数为nil时，打印错误信息</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printArr</span><span class="params">(arr)</span></span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> arr <span class="keyword">then</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;数组不能为空！&#x27;</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">for</span> index, value <span class="keyword">in</span> <span class="built_in">ipairs</span>(arr) <span class="keyword">do</span></span><br><span class="line">        <span class="built_in">print</span>(value)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>





<h1 id="4-实现多级缓存"><a href="#4-实现多级缓存" class="headerlink" title="4.实现多级缓存"></a>4.实现多级缓存</h1><p>多级缓存的实现离不开Nginx编程，而Nginx编程又离不开OpenResty。</p>
<h2 id="4-1-安装OpenResty"><a href="#4-1-安装OpenResty" class="headerlink" title="4.1.安装OpenResty"></a>4.1.安装OpenResty</h2><p>OpenResty® 是一个基于 Nginx的高性能 Web 平台，用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。具备下列特点：</p>
<ul>
<li>具备Nginx的完整功能</li>
<li>基于Lua语言进行扩展，集成了大量精良的 Lua 库、第三方模块</li>
<li>允许使用Lua<strong>自定义业务逻辑</strong>、<strong>自定义库</strong></li>
</ul>
<p>官方网站： <a target="_blank" rel="noopener" href="https://openresty.org/cn/">https://openresty.org/cn/</a></p>
<p><img src="/xlrblog/assets/image-20210821092902946.png" alt="image-20210821092902946"></p>
<p>安装OpenResty可以参考课前资料提供的《安装OpenResty.md》：</p>
<p><img src="/xlrblog/assets/image-20210821092941139.png" alt="image-20210821092941139"> </p>
<h3 id="1-安装"><a href="#1-安装" class="headerlink" title="1.安装"></a>1.安装</h3><p>首先你的Linux虚拟机必须联网</p>
<h4 id="1）安装"><a href="#1）安装" class="headerlink" title="1）安装"></a>1）安装</h4><h4 id="5）目录结构"><a href="#5）目录结构" class="headerlink" title="5）目录结构"></a><strong>5）目录结构</strong></h4><p>默认情况下，OpenResty安装的目录是：&#x2F;usr&#x2F;local&#x2F;openresty</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">bin</span><br><span class="line">luajit</span><br><span class="line">lualib</span><br><span class="line">nginx</span><br><span class="line">openssl111</span><br><span class="line">pcre</span><br><span class="line">site</span><br><span class="line">zlib</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><img src="/xlrblog/../Spring%20Cloud%E7%AD%89/assets/image-20200310225539214.png" alt="image-20200310225539214"> </p>
<p>看到里面的nginx目录了吗，OpenResty就是在Nginx基础上集成了一些Lua模块。</p>
<h4 id="6）配置nginx的环境变量"><a href="#6）配置nginx的环境变量" class="headerlink" title="6）配置nginx的环境变量"></a><strong>6）配置nginx的环境变量</strong></h4><p>打开配置文件：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vi /etc/profile</span><br></pre></td></tr></table></figure>

<p>在最下面加入两行：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">export</span> NGINX_HOME=/usr/local/openresty/nginx</span><br><span class="line"><span class="built_in">export</span> PATH=<span class="variable">$&#123;NGINX_HOME&#125;</span>/sbin:<span class="variable">$PATH</span></span><br></pre></td></tr></table></figure>

<p>NGINX_HOME：后面是OpenResty安装目录下的nginx的目录</p>
<p>然后让配置生效：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">source /etc/profile</span><br></pre></td></tr></table></figure>



<h3 id="2-启动和运行"><a href="#2-启动和运行" class="headerlink" title="2.启动和运行"></a>2.启动和运行</h3><p>OpenResty底层是基于Nginx的，查看OpenResty目录的nginx目录，结构与windows中安装的nginx基本一致：</p>
<p><img src="/xlrblog/../Spring%20Cloud%E7%AD%89/assets/image-20210811100653291.png" alt="image-20210811100653291"></p>
<p>所以运行方式与nginx基本一致：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 启动nginx</span></span><br><span class="line">nginx</span><br><span class="line"><span class="comment"># 重新加载配置</span></span><br><span class="line">nginx -s reload</span><br><span class="line"><span class="comment"># 停止</span></span><br><span class="line">nginx -s stop</span><br></pre></td></tr></table></figure>





<p>nginx的默认配置文件注释太多，影响后续我们的编辑，这里将nginx.conf中的注释部分删除，保留有效部分。</p>
<p>修改<code>/usr/local/openresty/nginx/conf/nginx.conf</code>文件，内容如下：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#user  nobody;</span></span><br><span class="line"><span class="attribute">worker_processes</span>  <span class="number">1</span>;</span><br><span class="line"><span class="attribute">error_log</span>  logs/<span class="literal">error</span>.log;</span><br><span class="line"></span><br><span class="line"><span class="section">events</span> &#123;</span><br><span class="line">    <span class="attribute">worker_connections</span>  <span class="number">1024</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="section">http</span> &#123;</span><br><span class="line">    <span class="attribute">include</span>       mime.types;</span><br><span class="line">    <span class="attribute">default_type</span>  application/octet-stream;</span><br><span class="line">    <span class="attribute">sendfile</span>        <span class="literal">on</span>;</span><br><span class="line">    <span class="attribute">keepalive_timeout</span>  <span class="number">65</span>;</span><br><span class="line"></span><br><span class="line">    <span class="section">server</span> &#123;</span><br><span class="line">        <span class="attribute">listen</span>       <span class="number">8081</span>;</span><br><span class="line">        <span class="attribute">server_name</span>  localhost;</span><br><span class="line">        <span class="section">location</span> / &#123;</span><br><span class="line">            <span class="attribute">root</span>   html;</span><br><span class="line">            <span class="attribute">index</span>  index.html index.htm;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="attribute">error_page</span>   <span class="number">500</span> <span class="number">502</span> <span class="number">503</span> <span class="number">504</span>  /50x.html;</span><br><span class="line">        <span class="section">location</span> = /50x.html &#123;</span><br><span class="line">            <span class="attribute">root</span>   html;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>在Linux的控制台输入命令以启动nginx：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nginx</span><br></pre></td></tr></table></figure>



<p>然后访问页面：<a href="http://192.168.150.101:8081，注意ip地址替换为你自己的虚拟机IP：">http://192.168.150.101:8081，注意ip地址替换为你自己的虚拟机IP：</a></p>
<h3 id="3-备注"><a href="#3-备注" class="headerlink" title="3.备注"></a>3.备注</h3><p>加载OpenResty的lua模块：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#lua 模块</span></span><br><span class="line"><span class="attribute">lua_package_path</span> <span class="string">&quot;/usr/local/openresty/lualib/?.lua;;&quot;</span>;</span><br><span class="line"><span class="comment">#c模块     </span></span><br><span class="line"><span class="attribute">lua_package_cpath</span> <span class="string">&quot;/usr/local/openresty/lualib/?.so;;&quot;</span>;  </span><br></pre></td></tr></table></figure>



<p>common.lua</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 封装函数，发送http请求，并解析响应</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">read_http</span><span class="params">(path, params)</span></span></span><br><span class="line">    <span class="keyword">local</span> resp = ngx.location.capture(<span class="built_in">path</span>,&#123;</span><br><span class="line">        method = ngx.HTTP_GET,</span><br><span class="line">        args = params,</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> resp <span class="keyword">then</span></span><br><span class="line">        <span class="comment">-- 记录错误信息，返回404</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;http not found, path: &quot;</span>, <span class="built_in">path</span> , <span class="string">&quot;, args: &quot;</span>, args)</span><br><span class="line">        ngx.<span class="built_in">exit</span>(<span class="number">404</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">return</span> resp.body</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 将方法导出</span></span><br><span class="line"><span class="keyword">local</span> _M = &#123;  </span><br><span class="line">    read_http = read_http</span><br><span class="line">&#125;  </span><br><span class="line"><span class="keyword">return</span> _M</span><br></pre></td></tr></table></figure>



<p>释放Redis连接API：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 关闭redis连接的工具方法，其实是放入连接池</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">close_redis</span><span class="params">(red)</span></span></span><br><span class="line">    <span class="keyword">local</span> pool_max_idle_time = <span class="number">10000</span> <span class="comment">-- 连接的空闲时间，单位是毫秒</span></span><br><span class="line">    <span class="keyword">local</span> pool_size = <span class="number">100</span> <span class="comment">--连接池大小</span></span><br><span class="line">    <span class="keyword">local</span> ok, err = red:set_keepalive(pool_max_idle_time, pool_size)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> ok <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;放入redis连接池失败: &quot;</span>, err)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>

<p>读取Redis数据的API：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 查询redis的方法 ip和port是redis地址，key是查询的key</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">read_redis</span><span class="params">(ip, port, key)</span></span></span><br><span class="line">    <span class="comment">-- 获取一个连接</span></span><br><span class="line">    <span class="keyword">local</span> ok, err = red:connect(ip, port)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> ok <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;连接redis失败 : &quot;</span>, err)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 查询redis</span></span><br><span class="line">    <span class="keyword">local</span> resp, err = red:get(key)</span><br><span class="line">    <span class="comment">-- 查询失败处理</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> resp <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;查询Redis失败: &quot;</span>, err, <span class="string">&quot;, key = &quot;</span> , key)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">--得到的数据为空处理</span></span><br><span class="line">    <span class="keyword">if</span> resp == ngx.null <span class="keyword">then</span></span><br><span class="line">        resp = <span class="literal">nil</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;查询Redis数据为空, key = &quot;</span>, key)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    close_redis(red)</span><br><span class="line">    <span class="keyword">return</span> resp</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>



<p>开启共享词典：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 共享字典，也就是本地缓存，名称叫做：item_cache，大小150m</span></span><br><span class="line"><span class="attribute">lua_shared_dict</span> item_cache <span class="number">150m</span>; </span><br></pre></td></tr></table></figure>





<h2 id="4-2-OpenResty快速入门"><a href="#4-2-OpenResty快速入门" class="headerlink" title="4.2.OpenResty快速入门"></a>4.2.OpenResty快速入门</h2><p>我们希望达到的多级缓存架构如图：</p>
<p><img src="/xlrblog/assets/yeVDlwtfMx.png" alt="yeVDlwtfMx"></p>
<p>其中：</p>
<ul>
<li><p>windows上的nginx用来做反向代理服务，将前端的查询商品的ajax请求代理到OpenResty集群</p>
</li>
<li><p>OpenResty集群用来编写多级缓存业务</p>
</li>
</ul>
<h3 id="4-2-1-反向代理流程"><a href="#4-2-1-反向代理流程" class="headerlink" title="4.2.1.反向代理流程"></a>4.2.1.反向代理流程</h3><p>现在，商品详情页使用的是假的商品数据。不过在浏览器中，可以看到页面有发起ajax请求查询真实商品数据。</p>
<p>这个请求如下：</p>
<p><img src="/xlrblog/assets/image-20210821093144700.png" alt="image-20210821093144700"></p>
<p>请求地址是localhost，端口是80，就被windows上安装的Nginx服务给接收到了。然后代理给了OpenResty集群：</p>
<p><img src="/xlrblog/assets/image-20210821094447709.png" alt="image-20210821094447709"></p>
<p>我们需要在OpenResty中编写业务，查询商品数据并返回到浏览器。</p>
<p>但是这次，我们先在OpenResty接收请求，返回假的商品数据。</p>
<h3 id="4-2-2-OpenResty监听请求"><a href="#4-2-2-OpenResty监听请求" class="headerlink" title="4.2.2.OpenResty监听请求"></a>4.2.2.OpenResty监听请求</h3><p>OpenResty的很多功能都依赖于其目录下的Lua库，需要在nginx.conf中指定依赖库的目录，并导入依赖：</p>
<p>1）添加对OpenResty的Lua模块的加载</p>
<p>修改<code>/usr/local/openresty/nginx/conf/nginx.conf</code>文件，在其中的http下面，添加下面代码：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#lua 模块</span></span><br><span class="line"><span class="attribute">lua_package_path</span> <span class="string">&quot;/usr/local/openresty/lualib/?.lua;;&quot;</span>;</span><br><span class="line"><span class="comment">#c模块     </span></span><br><span class="line"><span class="attribute">lua_package_cpath</span> <span class="string">&quot;/usr/local/openresty/lualib/?.so;;&quot;</span>;  </span><br></pre></td></tr></table></figure>



<p>2）监听&#x2F;api&#x2F;item路径</p>
<p>修改<code>/usr/local/openresty/nginx/conf/nginx.conf</code>文件，在nginx.conf的server下面，添加对&#x2F;api&#x2F;item这个路径的监听：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">location</span>  /api/item &#123;</span><br><span class="line">    <span class="comment"># 默认的响应类型</span></span><br><span class="line">    <span class="attribute">default_type</span> application/json;</span><br><span class="line">    <span class="comment"># 响应结果由lua/item.lua文件来决定</span></span><br><span class="line">    <span class="attribute">content_by_lua_file</span> lua/item.lua;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>这个监听，就类似于SpringMVC中的<code>@GetMapping(&quot;/api/item&quot;)</code>做路径映射。</p>
<p>而<code>content_by_lua_file lua/item.lua</code>则相当于调用item.lua这个文件，执行其中的业务，把结果返回给用户。相当于java中调用service。</p>
<h3 id="4-2-3-编写item-lua"><a href="#4-2-3-编写item-lua" class="headerlink" title="4.2.3.编写item.lua"></a>4.2.3.编写item.lua</h3><p>1）在<code>/usr/loca/openresty/nginx</code>目录创建文件夹：lua</p>
<p><img src="/xlrblog/assets/image-20210821100755080.png" alt="image-20210821100755080"></p>
<p>2）在<code>/usr/loca/openresty/nginx/lua</code>文件夹下，新建文件：item.lua</p>
<p><img src="/xlrblog/assets/image-20210821100801756.png" alt="image-20210821100801756"></p>
<p>3）编写item.lua，返回假数据</p>
<p>item.lua中，利用ngx.say()函数返回数据到Response中</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ngx.say(<span class="string">&#x27;&#123;&quot;id&quot;:10001,&quot;name&quot;:&quot;SALSA AIR&quot;,&quot;title&quot;:&quot;RIMOWA 21寸托运箱拉杆箱 SALSA AIR系列果绿色 820.70.36.4&quot;,&quot;price&quot;:17900,&quot;image&quot;:&quot;https://m.360buyimg.com/mobilecms/s720x720_jfs/t6934/364/1195375010/84676/e9f2c55f/597ece38N0ddcbc77.jpg!q70.jpg.webp&quot;,&quot;category&quot;:&quot;拉杆箱&quot;,&quot;brand&quot;:&quot;RIMOWA&quot;,&quot;spec&quot;:&quot;&quot;,&quot;status&quot;:1,&quot;createTime&quot;:&quot;2019-04-30T16:00:00.000+00:00&quot;,&quot;updateTime&quot;:&quot;2019-04-30T16:00:00.000+00:00&quot;,&quot;stock&quot;:2999,&quot;sold&quot;:31290&#125;&#x27;</span>)</span><br></pre></td></tr></table></figure>



<p>4）重新加载配置</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nginx -s reload</span><br></pre></td></tr></table></figure>



<p>刷新商品页面：<a target="_blank" rel="noopener" href="http://localhost/item.html?id=1001%EF%BC%8C%E5%8D%B3%E5%8F%AF%E7%9C%8B%E5%88%B0%E6%95%88%E6%9E%9C%EF%BC%9A">http://localhost/item.html?id=1001，即可看到效果：</a></p>
<p><img src="/xlrblog/assets/image-20210821101217089.png" alt="image-20210821101217089"></p>
<h2 id="4-3-请求参数处理"><a href="#4-3-请求参数处理" class="headerlink" title="4.3.请求参数处理"></a>4.3.请求参数处理</h2><p>上一节中，我们在OpenResty接收前端请求，但是返回的是假数据。</p>
<p>要返回真实数据，必须根据前端传递来的商品id，查询商品信息才可以。</p>
<p>那么如何获取前端传递的商品参数呢？</p>
<h3 id="4-3-1-获取参数的API"><a href="#4-3-1-获取参数的API" class="headerlink" title="4.3.1.获取参数的API"></a>4.3.1.获取参数的API</h3><p>OpenResty中提供了一些API用来获取不同类型的前端请求参数：</p>
<table>
<thead>
<tr>
<th>参数格式</th>
<th>参数示例</th>
<th>参数解析代码示例</th>
</tr>
</thead>
<tbody><tr>
<td>路径占位符</td>
<td>&#x2F;item&#x2F;1001</td>
<td>1.正则表达式匹配： location ~ &#x2F;item&#x2F;(\d+) {     content_by_lua_file lua&#x2F;item.lua;}– 2. 匹配到的参数会存入ngx.var数组中，可以用角标获取， local id &#x3D; ngx.var[1]</td>
</tr>
<tr>
<td>请求头</td>
<td>id：1001</td>
<td>– 获取请求头，返回值是table类型   local headers &#x3D; ngx.req.get_headers()</td>
</tr>
<tr>
<td>Get请求参数</td>
<td>?id&#x3D;1001</td>
<td>– 获取GET请求参数，返回值是table类型   local getParams &#x3D; ngx.req.get_uri_args()</td>
</tr>
<tr>
<td>Post表单参数</td>
<td>id&#x3D;1001</td>
<td>– 读取请求体   ngx.req.read_body()   – 获取POST表单参数，返回值是table类型   local postParams &#x3D; ngx.req.get_post_args()</td>
</tr>
<tr>
<td>JSON参数</td>
<td>{“id”:   1001}</td>
<td>– 读取请求体   ngx.req.read_body()   – 获取body中的json参数，返回值是string类型   local jsonBody &#x3D; ngx.req.get_body_data()</td>
</tr>
</tbody></table>
<p><img src="/xlrblog/assets/image-20210821101433528.png" alt="image-20210821101433528"></p>
<h3 id="4-3-2-获取参数并返回"><a href="#4-3-2-获取参数并返回" class="headerlink" title="4.3.2.获取参数并返回"></a>4.3.2.获取参数并返回</h3><p>在前端发起的ajax请求如图：</p>
<p><img src="/xlrblog/assets/image-20210821101721649.png" alt="image-20210821101721649"></p>
<p>可以看到商品id是以路径占位符方式传递的，因此可以利用正则表达式匹配的方式来获取ID</p>
<p>1）获取商品id</p>
<p>修改<code>/usr/loca/openresty/nginx/nginx.conf</code>文件中监听&#x2F;api&#x2F;item的代码，利用正则表达式获取ID：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">location</span> <span class="regexp">~ /api/item/(\d+)</span> &#123;</span><br><span class="line">    <span class="comment"># 默认的响应类型</span></span><br><span class="line">    <span class="attribute">default_type</span> application/json;</span><br><span class="line">    <span class="comment"># 响应结果由lua/item.lua文件来决定</span></span><br><span class="line">    <span class="attribute">content_by_lua_file</span> lua/item.lua;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>2）拼接ID并返回</p>
<p>修改<code>/usr/loca/openresty/nginx/lua/item.lua</code>文件，获取id并拼接到结果中返回：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 获取商品id</span></span><br><span class="line"><span class="keyword">local</span> id = ngx.var[<span class="number">1</span>]</span><br><span class="line"><span class="comment">-- 拼接并返回</span></span><br><span class="line">ngx.say(<span class="string">&#x27;&#123;&quot;id&quot;:&#x27;</span> .. id .. <span class="string">&#x27;,&quot;name&quot;:&quot;SALSA AIR&quot;,&quot;title&quot;:&quot;RIMOWA 21寸托运箱拉杆箱 SALSA AIR系列果绿色 820.70.36.4&quot;,&quot;price&quot;:17900,&quot;image&quot;:&quot;https://m.360buyimg.com/mobilecms/s720x720_jfs/t6934/364/1195375010/84676/e9f2c55f/597ece38N0ddcbc77.jpg!q70.jpg.webp&quot;,&quot;category&quot;:&quot;拉杆箱&quot;,&quot;brand&quot;:&quot;RIMOWA&quot;,&quot;spec&quot;:&quot;&quot;,&quot;status&quot;:1,&quot;createTime&quot;:&quot;2019-04-30T16:00:00.000+00:00&quot;,&quot;updateTime&quot;:&quot;2019-04-30T16:00:00.000+00:00&quot;,&quot;stock&quot;:2999,&quot;sold&quot;:31290&#125;&#x27;</span>)</span><br></pre></td></tr></table></figure>



<p>3）重新加载并测试</p>
<p>运行命令以重新加载OpenResty配置：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nginx -s reload</span><br></pre></td></tr></table></figure>



<p>刷新页面可以看到结果中已经带上了ID：</p>
<p><img src="/xlrblog/assets/image-20210821102235467.png" alt="image-20210821102235467"> </p>
<h2 id="4-4-查询Tomcat"><a href="#4-4-查询Tomcat" class="headerlink" title="4.4.查询Tomcat"></a>4.4.查询Tomcat</h2><p>拿到商品ID后，本应去缓存中查询商品信息，不过目前我们还未建立nginx、redis缓存。因此，这里我们先根据商品id去tomcat查询商品信息。我们实现如图部分：</p>
<p><img src="/xlrblog/assets/image-20210821102610167.png" alt="image-20210821102610167"></p>
<p>需要注意的是，我们的OpenResty是在虚拟机，Tomcat是在Windows电脑上。两者IP一定不要搞错了。</p>
<p><img src="/xlrblog/assets/image-20210821102959829.png" alt="image-20210821102959829"></p>
<h3 id="4-4-1-发送http请求的API"><a href="#4-4-1-发送http请求的API" class="headerlink" title="4.4.1.发送http请求的API"></a>4.4.1.发送http请求的API</h3><p>nginx提供了内部API用以发送http请求：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> resp = ngx.location.capture(<span class="string">&quot;/path&quot;</span>,&#123;</span><br><span class="line">    method = ngx.HTTP_GET,   <span class="comment">-- 请求方式</span></span><br><span class="line">    args = &#123;a=<span class="number">1</span>,b=<span class="number">2</span>&#125;,  <span class="comment">-- get方式传参数</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>返回的响应内容包括：</p>
<ul>
<li>resp.status：响应状态码</li>
<li>resp.header：响应头，是一个table</li>
<li>resp.body：响应体，就是响应数据</li>
</ul>
<p>注意：这里的path是路径，并不包含IP和端口。这个请求会被nginx内部的server监听并处理。</p>
<p>但是我们希望这个请求发送到Tomcat服务器，所以还需要编写一个server来对这个路径做反向代理：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">location</span> /path &#123;</span><br><span class="line">    <span class="comment"># 这里是windows电脑的ip和Java服务端口，需要确保windows防火墙处于关闭状态</span></span><br><span class="line">    <span class="attribute">proxy_pass</span> http://192.168.150.1:8081; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>原理如图：</p>
<p><img src="/xlrblog/assets/image-20210821104149061.png" alt="image-20210821104149061"></p>
<h3 id="4-4-2-封装http工具"><a href="#4-4-2-封装http工具" class="headerlink" title="4.4.2.封装http工具"></a>4.4.2.封装http工具</h3><p>下面，我们封装一个发送Http请求的工具，基于ngx.location.capture来实现查询tomcat。</p>
<p>1）添加反向代理，到windows的Java服务</p>
<p>因为item-service中的接口都是&#x2F;item开头，所以我们监听&#x2F;item路径，代理到windows上的tomcat服务。</p>
<p>修改 <code>/usr/local/openresty/nginx/conf/nginx.conf</code>文件，添加一个location：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">location</span> /item &#123;</span><br><span class="line">    <span class="attribute">proxy_pass</span> http://192.168.150.1:8081;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>以后，只要我们调用<code>ngx.location.capture(&quot;/item&quot;)</code>，就一定能发送请求到windows的tomcat服务。</p>
<p>2）封装工具类</p>
<p>之前我们说过，OpenResty启动时会加载以下两个目录中的工具文件：</p>
<p><img src="/xlrblog/assets/image-20210821104857413.png" alt="image-20210821104857413"></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">#lua 模块</span><br><span class="line">lua_package_path &quot;/usr/local/openresty/lualib/?.lua;;&quot;;</span><br><span class="line">#c模块     </span><br><span class="line">lua_package_cpath &quot;/usr/local/openresty/lualib/?.so;;&quot;;  </span><br></pre></td></tr></table></figure>



<p>所以，自定义的http工具也需要放到这个目录下。</p>
<p>在<code>/usr/local/openresty/lualib</code>目录下，新建一个common.lua文件：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vi /usr/local/openresty/lualib/common.lua</span><br></pre></td></tr></table></figure>

<p>内容如下:</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 封装函数，发送http请求，并解析响应</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">read_http</span><span class="params">(path, params)</span></span></span><br><span class="line">    <span class="keyword">local</span> resp = ngx.location.capture(<span class="built_in">path</span>,&#123;</span><br><span class="line">        method = ngx.HTTP_GET,</span><br><span class="line">        args = params,</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> resp <span class="keyword">then</span></span><br><span class="line">        <span class="comment">-- 记录错误信息，返回404</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;http请求查询失败, path: &quot;</span>, <span class="built_in">path</span> , <span class="string">&quot;, args: &quot;</span>, args)</span><br><span class="line">        ngx.<span class="built_in">exit</span>(<span class="number">404</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">return</span> resp.body</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 将方法导出</span></span><br><span class="line"><span class="keyword">local</span> _M = &#123;  </span><br><span class="line">    read_http = read_http</span><br><span class="line">&#125;  </span><br><span class="line"><span class="keyword">return</span> _M</span><br></pre></td></tr></table></figure>



<p>这个工具将read_http函数封装到_M这个table类型的变量中，并且返回，这类似于导出。</p>
<p>使用的时候，可以利用<code>require(&#39;common&#39;)</code>来导入该函数库，这里的common是函数库的文件名。</p>
<p>3）实现商品查询</p>
<p>最后，我们修改<code>/usr/local/openresty/nginx/lua/item.lua</code>文件，利用刚刚封装的函数库实现对tomcat的查询：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 引入自定义common工具模块，返回值是common中返回的 _M</span></span><br><span class="line"><span class="keyword">local</span> common = <span class="built_in">require</span>(<span class="string">&quot;common&quot;</span>)</span><br><span class="line"><span class="comment">-- 从 common中获取read_http这个函数</span></span><br><span class="line"><span class="keyword">local</span> read_http = common.read_http</span><br><span class="line"><span class="comment">-- 获取路径参数</span></span><br><span class="line"><span class="keyword">local</span> id = ngx.var[<span class="number">1</span>]</span><br><span class="line"><span class="comment">-- 根据id查询商品</span></span><br><span class="line"><span class="keyword">local</span> itemJSON = read_http(<span class="string">&quot;/item/&quot;</span>.. id, <span class="literal">nil</span>)</span><br><span class="line"><span class="comment">-- 根据id查询商品库存</span></span><br><span class="line"><span class="keyword">local</span> itemStockJSON = read_http(<span class="string">&quot;/item/stock/&quot;</span>.. id, <span class="literal">nil</span>)</span><br></pre></td></tr></table></figure>



<p>这里查询到的结果是json字符串，并且包含商品、库存两个json字符串，页面最终需要的是把两个json拼接为一个json：</p>
<p><img src="/xlrblog/assets/image-20210821110441222.png" alt="image-20210821110441222"></p>
<p>这就需要我们先把JSON变为lua的table，完成数据整合后，再转为JSON。</p>
<h3 id="4-4-3-CJSON工具类"><a href="#4-4-3-CJSON工具类" class="headerlink" title="4.4.3.CJSON工具类"></a>4.4.3.CJSON工具类</h3><p>OpenResty提供了一个cjson的模块用来处理JSON的序列化和反序列化。</p>
<p>官方地址： <a target="_blank" rel="noopener" href="https://github.com/openresty/lua-cjson/">https://github.com/openresty/lua-cjson/</a></p>
<p>1）引入cjson模块：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> cjson = <span class="built_in">require</span> <span class="string">&quot;cjson&quot;</span></span><br></pre></td></tr></table></figure>



<p>2）序列化：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> obj = &#123;</span><br><span class="line">    name = <span class="string">&#x27;jack&#x27;</span>,</span><br><span class="line">    age = <span class="number">21</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">-- 把 table 序列化为 json</span></span><br><span class="line"><span class="keyword">local</span> json = cjson.encode(obj)</span><br></pre></td></tr></table></figure>



<p>3）反序列化：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> json = <span class="string">&#x27;&#123;&quot;name&quot;: &quot;jack&quot;, &quot;age&quot;: 21&#125;&#x27;</span></span><br><span class="line"><span class="comment">-- 反序列化 json为 table</span></span><br><span class="line"><span class="keyword">local</span> obj = cjson.decode(json);</span><br><span class="line"><span class="built_in">print</span>(obj.name)</span><br></pre></td></tr></table></figure>





<h3 id="4-4-4-实现Tomcat查询"><a href="#4-4-4-实现Tomcat查询" class="headerlink" title="4.4.4.实现Tomcat查询"></a>4.4.4.实现Tomcat查询</h3><p>下面，我们修改之前的item.lua中的业务，添加json处理功能：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 导入common函数库</span></span><br><span class="line"><span class="keyword">local</span> common = <span class="built_in">require</span>(<span class="string">&#x27;common&#x27;</span>)</span><br><span class="line"><span class="keyword">local</span> read_http = common.read_http</span><br><span class="line"><span class="comment">-- 导入cjson库</span></span><br><span class="line"><span class="keyword">local</span> cjson = <span class="built_in">require</span>(<span class="string">&#x27;cjson&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 获取路径参数</span></span><br><span class="line"><span class="keyword">local</span> id = ngx.var[<span class="number">1</span>]</span><br><span class="line"><span class="comment">-- 根据id查询商品</span></span><br><span class="line"><span class="keyword">local</span> itemJSON = read_http(<span class="string">&quot;/item/&quot;</span>.. id, <span class="literal">nil</span>)</span><br><span class="line"><span class="comment">-- 根据id查询商品库存</span></span><br><span class="line"><span class="keyword">local</span> itemStockJSON = read_http(<span class="string">&quot;/item/stock/&quot;</span>.. id, <span class="literal">nil</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- JSON转化为lua的table</span></span><br><span class="line"><span class="keyword">local</span> item = cjson.decode(itemJSON)</span><br><span class="line"><span class="keyword">local</span> stock = cjson.decode(itemStockJSON)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 组合数据</span></span><br><span class="line">item.stock = stock.stock</span><br><span class="line">item.sold = stock.sold</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 把item序列化为json 返回结果</span></span><br><span class="line">ngx.say(cjson.encode(item))</span><br></pre></td></tr></table></figure>



<h3 id="4-4-5-基于ID负载均衡"><a href="#4-4-5-基于ID负载均衡" class="headerlink" title="4.4.5.基于ID负载均衡"></a>4.4.5.基于ID负载均衡</h3><p>刚才的代码中，我们的tomcat是单机部署。而实际开发中，tomcat一定是集群模式：</p>
<p><img src="/xlrblog/assets/image-20210821111023255.png" alt="image-20210821111023255"></p>
<p>因此，OpenResty需要对tomcat集群做负载均衡。</p>
<p>而默认的负载均衡规则是轮询模式，当我们查询&#x2F;item&#x2F;10001时：</p>
<ul>
<li>第一次会访问8081端口的tomcat服务，在该服务内部就形成了JVM进程缓存</li>
<li>第二次会访问8082端口的tomcat服务，该服务内部没有JVM缓存（因为JVM缓存无法共享），会查询数据库</li>
<li>…</li>
</ul>
<p>你看，因为轮询的原因，第一次查询8081形成的JVM缓存并未生效，直到下一次再次访问到8081时才可以生效，缓存命中率太低了。</p>
<p>怎么办？</p>
<p>如果能让同一个商品，每次查询时都访问同一个tomcat服务，那么JVM缓存就一定能生效了。</p>
<p>也就是说，我们需要根据商品id做负载均衡，而不是轮询。</p>
<h4 id="1）原理"><a href="#1）原理" class="headerlink" title="1）原理"></a>1）原理</h4><p>nginx提供了基于请求路径做负载均衡的算法：</p>
<p>nginx根据请求路径做hash运算，把得到的数值对tomcat服务的数量取余，余数是几，就访问第几个服务，实现负载均衡。</p>
<p>例如：</p>
<ul>
<li>我们的请求路径是 &#x2F;item&#x2F;10001</li>
<li>tomcat总数为2台（8081、8082）</li>
<li>对请求路径&#x2F;item&#x2F;1001做hash运算求余的结果为1</li>
<li>则访问第一个tomcat服务，也就是8081</li>
</ul>
<p>只要id不变，每次hash运算结果也不会变，那就可以保证同一个商品，一直访问同一个tomcat服务，确保JVM缓存生效。</p>
<h4 id="2）实现"><a href="#2）实现" class="headerlink" title="2）实现"></a>2）实现</h4><p>修改<code>/usr/local/openresty/nginx/conf/nginx.conf</code>文件，实现基于ID做负载均衡。</p>
<p>首先，定义tomcat集群，并设置基于路径做负载均衡：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">upstream</span> tomcat-cluster &#123;</span><br><span class="line">    <span class="attribute">hash</span> <span class="variable">$request_uri</span>;</span><br><span class="line">    <span class="attribute">server</span> <span class="number">192.168.150.1:8081</span>;</span><br><span class="line">    <span class="attribute">server</span> <span class="number">192.168.150.1:8082</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后，修改对tomcat服务的反向代理，目标指向tomcat集群：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">location</span> /item &#123;</span><br><span class="line">    <span class="attribute">proxy_pass</span> http://tomcat-cluster;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>重新加载OpenResty</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nginx -s reload</span><br></pre></td></tr></table></figure>

<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#user  nobody;</span></span><br><span class="line"><span class="attribute">worker_processes</span>  <span class="number">1</span>;</span><br><span class="line"><span class="attribute">error_log</span>  logs/<span class="literal">error</span>.log;</span><br><span class="line"></span><br><span class="line"><span class="section">events</span> &#123;</span><br><span class="line">    <span class="attribute">worker_connections</span>  <span class="number">1024</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="section">http</span> &#123;</span><br><span class="line">    <span class="attribute">include</span>       mime.types;</span><br><span class="line">    <span class="attribute">default_type</span>  application/octet-stream;</span><br><span class="line">    <span class="attribute">sendfile</span>        <span class="literal">on</span>;</span><br><span class="line">    <span class="attribute">keepalive_timeout</span>  <span class="number">65</span>;</span><br><span class="line">    <span class="comment">#lua 模块</span></span><br><span class="line">    <span class="attribute">lua_package_path</span> <span class="string">&quot;/usr/local/openresty/lualib/?.lua;;&quot;</span>;</span><br><span class="line">    <span class="comment">#c模块     </span></span><br><span class="line">    <span class="attribute">lua_package_cpath</span> <span class="string">&quot;/usr/local/openresty/lualib/?.so;;&quot;</span>;  </span><br><span class="line"></span><br><span class="line">    <span class="section">upstream</span> tomcat-cluster &#123;</span><br><span class="line">        <span class="attribute">hash</span> <span class="variable">$request_uri</span>;</span><br><span class="line">        <span class="attribute">server</span> <span class="number">192.168.137.1:8081</span>;</span><br><span class="line">        <span class="attribute">server</span> <span class="number">192.168.137.1:8082</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="section">server</span> &#123;</span><br><span class="line">        <span class="attribute">listen</span>       <span class="number">8081</span>;</span><br><span class="line">        <span class="attribute">server_name</span>  localhost;</span><br><span class="line">        <span class="section">location</span> /item &#123;</span><br><span class="line">            <span class="attribute">proxy_pass</span> http://tomcat-cluster;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="section">location</span> <span class="regexp">~ /api/item/(\d+)</span> &#123;</span><br><span class="line">            <span class="comment"># 响应类型，这里返回json</span></span><br><span class="line">            <span class="attribute">default_type</span> application/json;</span><br><span class="line">            <span class="comment"># 响应数据由 lua/item.lua这个文件来决定</span></span><br><span class="line">            <span class="attribute">content_by_lua_file</span> lua/item.lua;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="section">location</span> / &#123;</span><br><span class="line">            <span class="attribute">root</span>   html;</span><br><span class="line">            <span class="attribute">index</span>  index.html index.htm;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="attribute">error_page</span>   <span class="number">500</span> <span class="number">502</span> <span class="number">503</span> <span class="number">504</span>  /50x.html;</span><br><span class="line">        <span class="section">location</span> = /50x.html &#123;</span><br><span class="line">            <span class="attribute">root</span>   html;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h4 id="3）测试"><a href="#3）测试" class="headerlink" title="3）测试"></a>3）测试</h4><p>启动两台tomcat服务：</p>
<p><img src="/xlrblog/assets/image-20210821112420464.png" alt="image-20210821112420464"></p>
<p>同时启动：</p>
<p><img src="/xlrblog/assets/image-20210821112444482.png" alt="image-20210821112444482"> </p>
<p>清空日志后，再次访问页面，可以看到不同id的商品，访问到了不同的tomcat服务：</p>
<p><img src="/xlrblog/assets/image-20210821112559965.png" alt="image-20210821112559965"></p>
<p><img src="/xlrblog/assets/image-20210821112637430.png" alt="image-20210821112637430"></p>
<h2 id="4-5-Redis缓存预热"><a href="#4-5-Redis缓存预热" class="headerlink" title="4.5.Redis缓存预热"></a>4.5.Redis缓存预热</h2><p>Redis缓存会面临冷启动问题：</p>
<p><strong>冷启动</strong>：服务刚刚启动时，Redis中并没有缓存，如果所有商品数据都在第一次查询时添加缓存，可能会给数据库带来较大压力。</p>
<p><strong>缓存预热</strong>：在实际开发中，我们可以利用大数据统计用户访问的热点数据，在项目启动时将这些热点数据提前查询并保存到Redis中。</p>
<p>我们数据量较少，并且没有数据统计相关功能，目前可以在启动时将所有数据都放入缓存中。</p>
<p>1）利用Docker安装Redis</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker run --name redis -p 6379:6379 -d redis redis-server --appendonly <span class="built_in">yes</span></span><br></pre></td></tr></table></figure>



<p>2）在item-service服务中引入Redis依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<p>3）配置Redis地址</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">redis:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="number">192.168</span><span class="number">.150</span><span class="number">.101</span></span><br></pre></td></tr></table></figure>



<p>4）编写初始化类</p>
<p>缓存预热需要在项目启动时完成，并且必须是拿到RedisTemplate之后。</p>
<p>这里我们利用InitializingBean接口来实现，因为InitializingBean可以在对象被Spring创建并且成员变量全部注入后执行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.heima.item.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.core.JsonProcessingException;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.pojo.Item;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.pojo.ItemStock;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.service.IItemService;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.service.IItemStockService;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.InitializingBean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.StringRedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RedisHandler</span> <span class="keyword">implements</span> <span class="title class_">InitializingBean</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> StringRedisTemplate redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> IItemService itemService;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> IItemStockService stockService;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">ObjectMapper</span> <span class="variable">MAPPER</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 初始化缓存</span></span><br><span class="line">        <span class="comment">// 1.查询商品信息</span></span><br><span class="line">        List&lt;Item&gt; itemList = itemService.list();</span><br><span class="line">        <span class="comment">// 2.放入缓存</span></span><br><span class="line">        <span class="keyword">for</span> (Item item : itemList) &#123;</span><br><span class="line">            <span class="comment">// 2.1.item序列化为JSON</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> MAPPER.writeValueAsString(item);</span><br><span class="line">            <span class="comment">// 2.2.存入redis</span></span><br><span class="line">            redisTemplate.opsForValue().set(<span class="string">&quot;item:id:&quot;</span> + item.getId(), json);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3.查询商品库存信息</span></span><br><span class="line">        List&lt;ItemStock&gt; stockList = stockService.list();</span><br><span class="line">        <span class="comment">// 4.放入缓存</span></span><br><span class="line">        <span class="keyword">for</span> (ItemStock stock : stockList) &#123;</span><br><span class="line">            <span class="comment">// 2.1.item序列化为JSON</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> MAPPER.writeValueAsString(stock);</span><br><span class="line">            <span class="comment">// 2.2.存入redis</span></span><br><span class="line">            redisTemplate.opsForValue().set(<span class="string">&quot;item:stock:id:&quot;</span> + stock.getId(), json);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h2 id="4-6-查询Redis缓存"><a href="#4-6-查询Redis缓存" class="headerlink" title="4.6.查询Redis缓存"></a>4.6.查询Redis缓存</h2><p>现在，Redis缓存已经准备就绪，我们可以再OpenResty中实现查询Redis的逻辑了。如下图红框所示：</p>
<p><img src="/xlrblog/assets/image-20210821113340111.png" alt="image-20210821113340111"></p>
<p>当请求进入OpenResty之后：</p>
<ul>
<li>优先查询Redis缓存</li>
<li>如果Redis缓存未命中，再查询Tomcat</li>
</ul>
<h3 id="4-6-1-封装Redis工具"><a href="#4-6-1-封装Redis工具" class="headerlink" title="4.6.1.封装Redis工具"></a>4.6.1.封装Redis工具</h3><p>OpenResty提供了操作Redis的模块，我们只要引入该模块就能直接使用。但是为了方便，我们将Redis操作封装到之前的common.lua工具库中。</p>
<p>修改<code>/usr/local/openresty/lualib/common.lua</code>文件：</p>
<p>1）引入Redis模块，并初始化Redis对象</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 导入redis</span></span><br><span class="line"><span class="keyword">local</span> redis = <span class="built_in">require</span>(<span class="string">&#x27;resty.redis&#x27;</span>)</span><br><span class="line"><span class="comment">-- 初始化redis</span></span><br><span class="line"><span class="keyword">local</span> red = redis:new()</span><br><span class="line">red:set_timeouts(<span class="number">1000</span>, <span class="number">1000</span>, <span class="number">1000</span>)</span><br></pre></td></tr></table></figure>



<p>2）封装函数，用来释放Redis连接，其实是放入连接池</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 关闭redis连接的工具方法，其实是放入连接池</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">close_redis</span><span class="params">(red)</span></span></span><br><span class="line">    <span class="keyword">local</span> pool_max_idle_time = <span class="number">10000</span> <span class="comment">-- 连接的空闲时间，单位是毫秒</span></span><br><span class="line">    <span class="keyword">local</span> pool_size = <span class="number">100</span> <span class="comment">--连接池大小</span></span><br><span class="line">    <span class="keyword">local</span> ok, err = red:set_keepalive(pool_max_idle_time, pool_size)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> ok <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;放入redis连接池失败: &quot;</span>, err)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>



<p>3）封装函数，根据key查询Redis数据</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 查询redis的方法 ip和port是redis地址，key是查询的key</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">read_redis</span><span class="params">(ip, port, key)</span></span></span><br><span class="line">    <span class="comment">-- 获取一个连接</span></span><br><span class="line">    <span class="keyword">local</span> ok, err = red:connect(ip, port)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> ok <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;连接redis失败 : &quot;</span>, err)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 查询redis</span></span><br><span class="line">    <span class="keyword">local</span> resp, err = red:get(key)</span><br><span class="line">    <span class="comment">-- 查询失败处理</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> resp <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;查询Redis失败: &quot;</span>, err, <span class="string">&quot;, key = &quot;</span> , key)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">--得到的数据为空处理</span></span><br><span class="line">    <span class="keyword">if</span> resp == ngx.null <span class="keyword">then</span></span><br><span class="line">        resp = <span class="literal">nil</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;查询Redis数据为空, key = &quot;</span>, key)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    close_redis(red)</span><br><span class="line">    <span class="keyword">return</span> resp</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>



<p>4）导出</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 将方法导出</span></span><br><span class="line"><span class="keyword">local</span> _M = &#123;  </span><br><span class="line">    read_http = read_http,</span><br><span class="line">    read_redis = read_redis</span><br><span class="line">&#125;  </span><br><span class="line"><span class="keyword">return</span> _M</span><br></pre></td></tr></table></figure>



<p>完整的common.lua：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 导入redis</span></span><br><span class="line"><span class="keyword">local</span> redis = <span class="built_in">require</span>(<span class="string">&#x27;resty.redis&#x27;</span>)</span><br><span class="line"><span class="comment">-- 初始化redis</span></span><br><span class="line"><span class="keyword">local</span> red = redis:new()</span><br><span class="line">red:set_timeouts(<span class="number">1000</span>, <span class="number">1000</span>, <span class="number">1000</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 关闭redis连接的工具方法，其实是放入连接池</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">close_redis</span><span class="params">(red)</span></span></span><br><span class="line">    <span class="keyword">local</span> pool_max_idle_time = <span class="number">10000</span> <span class="comment">-- 连接的空闲时间，单位是毫秒</span></span><br><span class="line">    <span class="keyword">local</span> pool_size = <span class="number">100</span> <span class="comment">--连接池大小</span></span><br><span class="line">    <span class="keyword">local</span> ok, err = red:set_keepalive(pool_max_idle_time, pool_size)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> ok <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;放入redis连接池失败: &quot;</span>, err)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 查询redis的方法 ip和port是redis地址，key是查询的key</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">read_redis</span><span class="params">(ip, port, key)</span></span></span><br><span class="line">    <span class="comment">-- 获取一个连接</span></span><br><span class="line">    <span class="keyword">local</span> ok, err = red:connect(ip, port)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> ok <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;连接redis失败 : &quot;</span>, err)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 查询redis</span></span><br><span class="line">    <span class="keyword">local</span> resp, err = red:get(key)</span><br><span class="line">    <span class="comment">-- 查询失败处理</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> resp <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;查询Redis失败: &quot;</span>, err, <span class="string">&quot;, key = &quot;</span> , key)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">--得到的数据为空处理</span></span><br><span class="line">    <span class="keyword">if</span> resp == ngx.null <span class="keyword">then</span></span><br><span class="line">        resp = <span class="literal">nil</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;查询Redis数据为空, key = &quot;</span>, key)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    close_redis(red)</span><br><span class="line">    <span class="keyword">return</span> resp</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 封装函数，发送http请求，并解析响应</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">read_http</span><span class="params">(path, params)</span></span></span><br><span class="line">    <span class="keyword">local</span> resp = ngx.location.capture(<span class="built_in">path</span>,&#123;</span><br><span class="line">        method = ngx.HTTP_GET,</span><br><span class="line">        args = params,</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> resp <span class="keyword">then</span></span><br><span class="line">        <span class="comment">-- 记录错误信息，返回404</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;http查询失败, path: &quot;</span>, <span class="built_in">path</span> , <span class="string">&quot;, args: &quot;</span>, args)</span><br><span class="line">        ngx.<span class="built_in">exit</span>(<span class="number">404</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">return</span> resp.body</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 将方法导出</span></span><br><span class="line"><span class="keyword">local</span> _M = &#123;  </span><br><span class="line">    read_http = read_http,</span><br><span class="line">    read_redis = read_redis</span><br><span class="line">&#125;  </span><br><span class="line"><span class="keyword">return</span> _M</span><br></pre></td></tr></table></figure>





<h3 id="4-6-2-实现Redis查询"><a href="#4-6-2-实现Redis查询" class="headerlink" title="4.6.2.实现Redis查询"></a>4.6.2.实现Redis查询</h3><p>接下来，我们就可以去修改item.lua文件，实现对Redis的查询了。</p>
<p>查询逻辑是：</p>
<ul>
<li>根据id查询Redis</li>
<li>如果查询失败则继续查询Tomcat</li>
<li>将查询结果返回</li>
</ul>
<p>1）修改<code>/usr/local/openresty/lua/item.lua</code>文件，添加一个查询函数：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 导入common函数库</span></span><br><span class="line"><span class="keyword">local</span> common = <span class="built_in">require</span>(<span class="string">&#x27;common&#x27;</span>)</span><br><span class="line"><span class="keyword">local</span> read_http = common.read_http</span><br><span class="line"><span class="keyword">local</span> read_redis = common.read_redis</span><br><span class="line"><span class="comment">-- 封装查询函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">read_data</span><span class="params">(key, path, params)</span></span></span><br><span class="line">    <span class="comment">-- 查询本地缓存</span></span><br><span class="line">    <span class="keyword">local</span> val = read_redis(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">6379</span>, key)</span><br><span class="line">    <span class="comment">-- 判断查询结果</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> val <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;redis查询失败，尝试查询http， key: &quot;</span>, key)</span><br><span class="line">        <span class="comment">-- redis查询失败，去查询http</span></span><br><span class="line">        val = read_http(<span class="built_in">path</span>, params)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 返回数据</span></span><br><span class="line">    <span class="keyword">return</span> val</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>



<p>2）而后修改商品查询、库存查询的业务：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 获取路径参数</span></span><br><span class="line"><span class="keyword">local</span> id = ngx.var[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 查询商品信息</span></span><br><span class="line"><span class="keyword">local</span> itemJSON = read_data(<span class="string">&quot;item:id:&quot;</span> .. id,  <span class="string">&quot;/item/&quot;</span> .. id, <span class="literal">nil</span>)</span><br><span class="line"><span class="comment">-- 查询库存信息</span></span><br><span class="line"><span class="keyword">local</span> stockJSON = read_data(<span class="string">&quot;item:stock:id:&quot;</span> .. id, <span class="string">&quot;/item/stock/&quot;</span> .. id, <span class="literal">nil</span>)</span><br></pre></td></tr></table></figure>

<p><img src="/xlrblog/assets/image-20210821114528954.png" alt="image-20210821114528954"></p>
<p>3）完整的item.lua代码：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 导入common函数库</span></span><br><span class="line"><span class="keyword">local</span> common = <span class="built_in">require</span>(<span class="string">&#x27;common&#x27;</span>)</span><br><span class="line"><span class="keyword">local</span> read_http = common.read_http</span><br><span class="line"><span class="keyword">local</span> read_redis = common.read_redis</span><br><span class="line"><span class="comment">-- 导入cjson库</span></span><br><span class="line"><span class="keyword">local</span> cjson = <span class="built_in">require</span>(<span class="string">&#x27;cjson&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 封装查询函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">read_data</span><span class="params">(key, path, params)</span></span></span><br><span class="line">    <span class="comment">-- 查询本地缓存</span></span><br><span class="line">    <span class="keyword">local</span> val = read_redis(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">6379</span>, key)</span><br><span class="line">    <span class="comment">-- 判断查询结果</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> val <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;redis查询失败，尝试查询http， key: &quot;</span>, key)</span><br><span class="line">        <span class="comment">-- redis查询失败，去查询http</span></span><br><span class="line">        val = read_http(<span class="built_in">path</span>, params)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 返回数据</span></span><br><span class="line">    <span class="keyword">return</span> val</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 获取路径参数</span></span><br><span class="line"><span class="keyword">local</span> id = ngx.var[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 查询商品信息</span></span><br><span class="line"><span class="keyword">local</span> itemJSON = read_data(<span class="string">&quot;item:id:&quot;</span> .. id,  <span class="string">&quot;/item/&quot;</span> .. id, <span class="literal">nil</span>)</span><br><span class="line"><span class="comment">-- 查询库存信息</span></span><br><span class="line"><span class="keyword">local</span> stockJSON = read_data(<span class="string">&quot;item:stock:id:&quot;</span> .. id, <span class="string">&quot;/item/stock/&quot;</span> .. id, <span class="literal">nil</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- JSON转化为lua的table</span></span><br><span class="line"><span class="keyword">local</span> item = cjson.decode(itemJSON)</span><br><span class="line"><span class="keyword">local</span> stock = cjson.decode(stockJSON)</span><br><span class="line"><span class="comment">-- 组合数据</span></span><br><span class="line">item.stock = stock.stock</span><br><span class="line">item.sold = stock.sold</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 把item序列化为json 返回结果</span></span><br><span class="line">ngx.say(cjson.encode(item))</span><br></pre></td></tr></table></figure>





<h2 id="4-7-Nginx本地缓存"><a href="#4-7-Nginx本地缓存" class="headerlink" title="4.7.Nginx本地缓存"></a>4.7.Nginx本地缓存</h2><p>现在，整个多级缓存中只差最后一环，也就是nginx的本地缓存了。如图：</p>
<p><img src="/xlrblog/assets/image-20210821114742950.png" alt="image-20210821114742950"></p>
<h3 id="4-7-1-本地缓存API"><a href="#4-7-1-本地缓存API" class="headerlink" title="4.7.1.本地缓存API"></a>4.7.1.本地缓存API</h3><p>OpenResty为Nginx提供了<strong>shard dict</strong>的功能，可以在nginx的多个worker之间共享数据，实现缓存功能。</p>
<p>1）开启共享字典，在nginx.conf的http下添加配置：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 共享字典，也就是本地缓存，名称叫做：item_cache，大小150m</span></span><br><span class="line"><span class="attribute">lua_shared_dict</span> item_cache <span class="number">150m</span>; </span><br></pre></td></tr></table></figure>



<p>2）操作共享字典：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 获取本地缓存对象</span></span><br><span class="line"><span class="keyword">local</span> item_cache = ngx.shared.item_cache</span><br><span class="line"><span class="comment">-- 存储, 指定key、value、过期时间，单位s，默认为0代表永不过期</span></span><br><span class="line">item_cache:set(<span class="string">&#x27;key&#x27;</span>, <span class="string">&#x27;value&#x27;</span>, <span class="number">1000</span>)</span><br><span class="line"><span class="comment">-- 读取</span></span><br><span class="line"><span class="keyword">local</span> val = item_cache:get(<span class="string">&#x27;key&#x27;</span>)</span><br></pre></td></tr></table></figure>



<h3 id="4-7-2-实现本地缓存查询"><a href="#4-7-2-实现本地缓存查询" class="headerlink" title="4.7.2.实现本地缓存查询"></a>4.7.2.实现本地缓存查询</h3><p>1）修改<code>/usr/local/openresty/lua/item.lua</code>文件，修改read_data查询函数，添加本地缓存逻辑：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 导入共享词典，本地缓存</span></span><br><span class="line"><span class="keyword">local</span> item_cache = ngx.shared.item_cache</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 封装查询函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">read_data</span><span class="params">(key, expire, path, params)</span></span></span><br><span class="line">    <span class="comment">-- 查询本地缓存</span></span><br><span class="line">    <span class="keyword">local</span> val = item_cache:get(key)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> val <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;本地缓存查询失败，尝试查询Redis， key: &quot;</span>, key)</span><br><span class="line">        <span class="comment">-- 查询redis</span></span><br><span class="line">        val = read_redis(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">6379</span>, key)</span><br><span class="line">        <span class="comment">-- 判断查询结果</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> val <span class="keyword">then</span></span><br><span class="line">            ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;redis查询失败，尝试查询http， key: &quot;</span>, key)</span><br><span class="line">            <span class="comment">-- redis查询失败，去查询http</span></span><br><span class="line">            val = read_http(<span class="built_in">path</span>, params)</span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 查询成功，把数据写入本地缓存</span></span><br><span class="line">    item_cache:set(key, val, expire)</span><br><span class="line">    <span class="comment">-- 返回数据</span></span><br><span class="line">    <span class="keyword">return</span> val</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>





<p>2）修改item.lua中查询商品和库存的业务，实现最新的read_data函数：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 查询商品信息</span></span><br><span class="line"><span class="keyword">local</span> itemJSON = read_data(<span class="string">&quot;item:id:&quot;</span> .. id, <span class="number">1800</span>,  <span class="string">&quot;/item/&quot;</span> .. id, <span class="literal">nil</span>)</span><br><span class="line"><span class="comment">-- 查询库存信息</span></span><br><span class="line"><span class="keyword">local</span> stockJSON = read_data(<span class="string">&quot;item:stock:id:&quot;</span> .. id, <span class="number">60</span>, <span class="string">&quot;/item/stock/&quot;</span> .. id, <span class="literal">nil</span>)</span><br></pre></td></tr></table></figure>

<p><img src="/xlrblog/assets/image-20210821115108528.png" alt="image-20210821115108528"></p>
<p>其实就是多了缓存时间参数，过期后nginx缓存会自动删除，下次访问即可更新缓存。</p>
<p>这里给商品基本信息设置超时时间为30分钟，库存为1分钟。</p>
<p>因为库存更新频率较高，如果缓存时间过长，可能与数据库差异较大。</p>
<p>3）完整的item.lua文件：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 导入common函数库</span></span><br><span class="line"><span class="keyword">local</span> common = <span class="built_in">require</span>(<span class="string">&#x27;common&#x27;</span>)</span><br><span class="line"><span class="keyword">local</span> read_http = common.read_http</span><br><span class="line"><span class="keyword">local</span> read_redis = common.read_redis</span><br><span class="line"><span class="comment">-- 导入cjson库</span></span><br><span class="line"><span class="keyword">local</span> cjson = <span class="built_in">require</span>(<span class="string">&#x27;cjson&#x27;</span>)</span><br><span class="line"><span class="comment">-- 导入共享词典，本地缓存</span></span><br><span class="line"><span class="keyword">local</span> item_cache = ngx.shared.item_cache</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 封装查询函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">read_data</span><span class="params">(key, expire, path, params)</span></span></span><br><span class="line">    <span class="comment">-- 查询本地缓存</span></span><br><span class="line">    <span class="keyword">local</span> val = item_cache:get(key)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> val <span class="keyword">then</span></span><br><span class="line">        ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;本地缓存查询失败，尝试查询Redis， key: &quot;</span>, key)</span><br><span class="line">        <span class="comment">-- 查询redis</span></span><br><span class="line">        val = read_redis(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">6379</span>, key)</span><br><span class="line">        <span class="comment">-- 判断查询结果</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> val <span class="keyword">then</span></span><br><span class="line">            ngx.<span class="built_in">log</span>(ngx.ERR, <span class="string">&quot;redis查询失败，尝试查询http， key: &quot;</span>, key)</span><br><span class="line">            <span class="comment">-- redis查询失败，去查询http</span></span><br><span class="line">            val = read_http(<span class="built_in">path</span>, params)</span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 查询成功，把数据写入本地缓存</span></span><br><span class="line">    item_cache:set(key, val, expire)</span><br><span class="line">    <span class="comment">-- 返回数据</span></span><br><span class="line">    <span class="keyword">return</span> val</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 获取路径参数</span></span><br><span class="line"><span class="keyword">local</span> id = ngx.var[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 查询商品信息</span></span><br><span class="line"><span class="keyword">local</span> itemJSON = read_data(<span class="string">&quot;item:id:&quot;</span> .. id, <span class="number">1800</span>,  <span class="string">&quot;/item/&quot;</span> .. id, <span class="literal">nil</span>)</span><br><span class="line"><span class="comment">-- 查询库存信息</span></span><br><span class="line"><span class="keyword">local</span> stockJSON = read_data(<span class="string">&quot;item:stock:id:&quot;</span> .. id, <span class="number">60</span>, <span class="string">&quot;/item/stock/&quot;</span> .. id, <span class="literal">nil</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- JSON转化为lua的table</span></span><br><span class="line"><span class="keyword">local</span> item = cjson.decode(itemJSON)</span><br><span class="line"><span class="keyword">local</span> stock = cjson.decode(stockJSON)</span><br><span class="line"><span class="comment">-- 组合数据</span></span><br><span class="line">item.stock = stock.stock</span><br><span class="line">item.sold = stock.sold</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 把item序列化为json 返回结果</span></span><br><span class="line">ngx.say(cjson.encode(item))</span><br></pre></td></tr></table></figure>





<h1 id="5-缓存同步"><a href="#5-缓存同步" class="headerlink" title="5.缓存同步"></a>5.缓存同步</h1><p>大多数情况下，浏览器查询到的都是缓存数据，如果缓存数据与数据库数据存在较大差异，可能会产生比较严重的后果。</p>
<p>所以我们必须保证数据库数据、缓存数据的一致性，这就是缓存与数据库的同步。</p>
<h2 id="5-1-数据同步策略"><a href="#5-1-数据同步策略" class="headerlink" title="5.1.数据同步策略"></a>5.1.数据同步策略</h2><p>缓存数据同步的常见方式有三种：</p>
<p><strong>设置有效期</strong>：给缓存设置有效期，到期后自动删除。再次查询时更新</p>
<ul>
<li>优势：简单、方便</li>
<li>缺点：时效性差，缓存过期之前可能不一致</li>
<li>场景：更新频率较低，时效性要求低的业务</li>
</ul>
<p><strong>同步双写</strong>：在修改数据库的同时，直接修改缓存</p>
<ul>
<li>优势：时效性强，缓存与数据库强一致</li>
<li>缺点：有代码侵入，耦合度高；</li>
<li>场景：对一致性、时效性要求较高的缓存数据</li>
</ul>
<p><strong>异步通知：</strong>修改数据库时发送事件通知，相关服务监听到通知后修改缓存数据</p>
<ul>
<li>优势：低耦合，可以同时通知多个缓存服务</li>
<li>缺点：时效性一般，可能存在中间不一致状态</li>
<li>场景：时效性要求一般，有多个服务需要同步</li>
</ul>
<p>而异步实现又可以基于MQ或者Canal来实现：</p>
<p>1）基于MQ的异步通知：</p>
<p><img src="/xlrblog/assets/image-20210821115552327.png" alt="image-20210821115552327"></p>
<p>解读：</p>
<ul>
<li>商品服务完成对数据的修改后，只需要发送一条消息到MQ中。</li>
<li>缓存服务监听MQ消息，然后完成对缓存的更新</li>
</ul>
<p>依然有少量的代码侵入。</p>
<p>2）基于Canal的通知</p>
<p><img src="/xlrblog/assets/image-20210821115719363.png" alt="image-20210821115719363"></p>
<p>解读：</p>
<ul>
<li>商品服务完成商品修改后，业务直接结束，没有任何代码侵入</li>
<li>Canal监听MySQL变化，当发现变化后，立即通知缓存服务</li>
<li>缓存服务接收到canal通知，更新缓存</li>
</ul>
<p>代码零侵入</p>
<h2 id="5-2-安装Canal"><a href="#5-2-安装Canal" class="headerlink" title="5.2.安装Canal"></a>5.2.安装Canal</h2><h3 id="5-2-1-认识Canal"><a href="#5-2-1-认识Canal" class="headerlink" title="5.2.1.认识Canal"></a>5.2.1.认识Canal</h3><p>**Canal [kə’næl]**，译意为水道&#x2F;管道&#x2F;沟渠，canal是阿里巴巴旗下的一款开源项目，基于Java开发。基于数据库增量日志解析，提供增量数据订阅&amp;消费。GitHub的地址：<a target="_blank" rel="noopener" href="https://github.com/alibaba/canal">https://github.com/alibaba/canal</a></p>
<p>Canal是基于mysql的主从同步来实现的，MySQL主从同步的原理如下：</p>
<p><img src="/xlrblog/assets/image-20210821115914748.png" alt="image-20210821115914748"></p>
<ul>
<li>1）MySQL master 将数据变更写入二进制日志( binary log），其中记录的数据叫做binary log events</li>
<li>2）MySQL slave 将 master 的 binary log events拷贝到它的中继日志(relay log)</li>
<li>3）MySQL slave 重放 relay log 中事件，将数据变更反映它自己的数据</li>
</ul>
<p>而Canal就是把自己伪装成MySQL的一个slave节点，从而监听master的binary log变化。再把得到的变化信息通知给Canal的客户端，进而完成对其它数据库的同步。</p>
<p><img src="/xlrblog/assets/image-20210821115948395.png" alt="image-20210821115948395"></p>
<h3 id="5-2-2-安装Canal"><a href="#5-2-2-安装Canal" class="headerlink" title="5.2.2.安装Canal"></a>5.2.2.安装Canal</h3><p>安装和配置Canal参考课前资料文档：</p>
<p><img src="/xlrblog/assets/image-20210821120017324.png" alt="image-20210821120017324"> </p>
<p>下面我们就开启mysql的主从同步机制，让Canal来模拟salve</p>
<h4 id="1-开启MySQL主从"><a href="#1-开启MySQL主从" class="headerlink" title="1.开启MySQL主从"></a>1.开启MySQL主从</h4><p>Canal是基于MySQL的主从同步功能，因此必须先开启MySQL的主从功能才可以。</p>
<p>这里以之前用Docker运行的mysql为例：</p>
<h5 id="1-1-开启binlog"><a href="#1-1-开启binlog" class="headerlink" title="1.1.开启binlog"></a>1.1.开启binlog</h5><p>打开mysql容器挂载的日志文件，我的在<code>/tmp/mysql/conf</code>目录:</p>
<p><img src="/xlrblog/../Spring%20Cloud%E7%AD%89/%E9%AB%98%E7%BA%A7%E7%AF%87/%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99/day04-%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98/%E8%B5%84%E6%96%99/assets/image-20210813153241537.png" alt="image-20210813153241537"></p>
<p>修改文件：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vi /tmp/mysql/conf/my.cnf</span><br></pre></td></tr></table></figure>

<p>添加内容：</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">log-bin</span>=/var/lib/mysql/mysql-bin</span><br><span class="line"><span class="attr">binlog-do-db</span>=heima</span><br></pre></td></tr></table></figure>

<p>配置解读：</p>
<ul>
<li><code>log-bin=/var/lib/mysql/mysql-bin</code>：设置binary log文件的存放地址和文件名，叫做mysql-bin</li>
<li><code>binlog-do-db=heima</code>：指定对哪个database记录binary log events，这里记录heima这个库</li>
</ul>
<p>最终效果：</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">[mysqld]</span></span><br><span class="line">skip-name-resolve</span><br><span class="line"><span class="attr">character_set_server</span>=utf8</span><br><span class="line"><span class="attr">datadir</span>=/var/lib/mysql</span><br><span class="line"><span class="attr">server-id</span>=<span class="number">1000</span></span><br><span class="line"><span class="attr">log-bin</span>=/var/lib/mysql/mysql-bin</span><br><span class="line"><span class="attr">binlog-do-db</span>=heima</span><br></pre></td></tr></table></figure>



<h5 id="1-2-设置用户权限"><a href="#1-2-设置用户权限" class="headerlink" title="1.2.设置用户权限"></a>1.2.设置用户权限</h5><p>接下来添加一个仅用于数据同步的账户，出于安全考虑，这里仅提供对heima这个库的操作权限。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">create user canal@&#x27;%&#x27; IDENTIFIED by &#x27;canal&#x27;;</span><br><span class="line">GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT,SUPER ON *.* TO &#x27;canal&#x27;@&#x27;%&#x27; identified by &#x27;canal&#x27;;</span><br><span class="line">FLUSH PRIVILEGES;</span><br></pre></td></tr></table></figure>



<p>重启mysql容器即可</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker restart mysql</span><br></pre></td></tr></table></figure>



<p>测试设置是否成功：在mysql控制台，或者Navicat中，输入命令：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show master status;</span><br></pre></td></tr></table></figure>

<p><img src="/xlrblog/../Spring%20Cloud%E7%AD%89/%E9%AB%98%E7%BA%A7%E7%AF%87/%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99/day04-%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98/%E8%B5%84%E6%96%99/assets/image-20200327094735948.png" alt="image-20200327094735948"></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&quot;File&quot;	&quot;Position&quot;	&quot;Binlog_Do_DB&quot;	&quot;Binlog_Ignore_DB&quot;	&quot;Executed_Gtid_Set&quot;</span><br><span class="line">&quot;mysql-bin.000001&quot;	&quot;863&quot;	&quot;heima&quot;	&quot;&quot;	&quot;&quot;</span><br></pre></td></tr></table></figure>

<h4 id="2-安装Canal"><a href="#2-安装Canal" class="headerlink" title="2.安装Canal"></a>2.安装Canal</h4><h5 id="2-1-创建网络"><a href="#2-1-创建网络" class="headerlink" title="2.1.创建网络"></a>2.1.创建网络</h5><p>我们需要创建一个网络，将MySQL、Canal、MQ放到同一个Docker网络中：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker network create heima</span><br></pre></td></tr></table></figure>

<p>让mysql加入这个网络：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker network connect heima mysql</span><br></pre></td></tr></table></figure>





<h5 id="2-3-安装Canal"><a href="#2-3-安装Canal" class="headerlink" title="2.3.安装Canal"></a>2.3.安装Canal</h5><p>课前资料中提供了canal的镜像压缩包:</p>
<p><img src="/xlrblog/../Spring%20Cloud%E7%AD%89/%E9%AB%98%E7%BA%A7%E7%AF%87/%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99/day04-%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98/%E8%B5%84%E6%96%99/assets/image-20210813161804292.png" alt="image-20210813161804292"> </p>
<p>大家可以上传到虚拟机，然后通过命令导入：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker load -i canal.tar</span><br></pre></td></tr></table></figure>

<p>查看镜像：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker images</span><br></pre></td></tr></table></figure>





<p>然后运行命令创建Canal容器：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">docker run -p 11111:11111 --name canal \</span><br><span class="line">-e canal.destinations=heima \</span><br><span class="line">-e canal.instance.master.address=mysql:3306  \</span><br><span class="line">-e canal.instance.dbUsername=canal  \</span><br><span class="line">-e canal.instance.dbPassword=canal  \</span><br><span class="line">-e canal.instance.connectionCharset=UTF-8 \</span><br><span class="line">-e canal.instance.tsdb.enable=<span class="literal">true</span> \</span><br><span class="line">-e canal.instance.gtidon=<span class="literal">false</span>  \</span><br><span class="line">-e canal.instance.filter.regex=heima\\..* \</span><br><span class="line">--network heima \</span><br><span class="line">-d canal/canal-server:v1.1.5</span><br></pre></td></tr></table></figure>

<p>查看运行日志：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker logs -f canal</span><br></pre></td></tr></table></figure>



<p>说明:</p>
<ul>
<li><code>-p 11111:11111</code>：这是canal的默认监听端口</li>
<li><code>-e canal.instance.master.address=mysql:3306</code>：数据库地址和端口，如果不知道mysql容器地址，可以通过<code>docker inspect 容器id</code>来查看</li>
<li><code>-e canal.instance.dbUsername=canal</code>：数据库用户名</li>
<li><code>-e canal.instance.dbPassword=canal</code> ：数据库密码</li>
<li><code>-e canal.instance.filter.regex=</code>：要监听的表名称</li>
</ul>
<p>表名称监听支持的语法：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql 数据解析关注的表，Perl正则表达式.</span><br><span class="line">多个正则之间以逗号(,)分隔，转义符需要双斜杠(\\) </span><br><span class="line">常见例子：</span><br><span class="line">1.  所有表：.*   or  .*\\..*</span><br><span class="line">2.  canal schema下所有表： canal\\..*</span><br><span class="line">3.  canal下的以canal打头的表：canal\\.canal.*</span><br><span class="line">4.  canal schema下的一张表：canal.test1</span><br><span class="line">5.  多个规则组合使用然后以逗号隔开：canal\\..*,mysql.test1,mysql.test2 </span><br></pre></td></tr></table></figure>



<p>进入容器内部：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker <span class="built_in">exec</span> -it canal bash</span><br></pre></td></tr></table></figure>

<p>查看日志：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">tail</span> -f canal-server/logs/canal/canal.log </span><br></pre></td></tr></table></figure>

<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">tail</span> -f canal-server/logs/heima/heima.log </span><br></pre></td></tr></table></figure>



<h2 id="5-3-监听Canal"><a href="#5-3-监听Canal" class="headerlink" title="5.3.监听Canal"></a>5.3.监听Canal</h2><p>Canal提供了各种语言的客户端，当Canal监听到binlog变化时，会通知Canal的客户端。</p>
<p><img src="/xlrblog/assets/image-20210821120049024.png" alt="image-20210821120049024"></p>
<p>我们可以利用Canal提供的Java客户端，监听Canal通知消息。当收到变化的消息时，完成对缓存的更新。</p>
<p>不过这里我们会使用GitHub上的第三方开源的canal-starter客户端。地址：<a target="_blank" rel="noopener" href="https://github.com/NormanGyllenhaal/canal-client">https://github.com/NormanGyllenhaal/canal-client</a></p>
<p>与SpringBoot完美整合，自动装配，比官方客户端要简单好用很多。</p>
<h3 id="5-3-1-引入依赖："><a href="#5-3-1-引入依赖：" class="headerlink" title="5.3.1.引入依赖："></a>5.3.1.引入依赖：</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>top.javatool<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>canal-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2.1-RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h3 id="5-3-2-编写配置："><a href="#5-3-2-编写配置：" class="headerlink" title="5.3.2.编写配置："></a>5.3.2.编写配置：</h3><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">canal:</span></span><br><span class="line">  <span class="attr">destination:</span> <span class="string">heima</span> <span class="comment"># canal的集群名字，要与安装canal时设置的名称一致</span></span><br><span class="line">  <span class="attr">server:</span> <span class="number">192.168</span><span class="number">.150</span><span class="number">.101</span><span class="string">:11111</span> <span class="comment"># canal服务地址</span></span><br></pre></td></tr></table></figure>



<h3 id="5-3-3-修改Item实体类"><a href="#5-3-3-修改Item实体类" class="headerlink" title="5.3.3.修改Item实体类"></a>5.3.3.修改Item实体类</h3><p>通过@Id、@Column、等注解完成Item与数据库表字段的映射：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.heima.item.pojo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.annotation.IdType;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.annotation.TableField;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.annotation.TableId;</span><br><span class="line"><span class="keyword">import</span> com.baomidou.mybatisplus.annotation.TableName;</span><br><span class="line"><span class="keyword">import</span> lombok.Data;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.annotation.Id;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.annotation.Transient;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.persistence.Column;</span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@TableName(&quot;tb_item&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Item</span> &#123;</span><br><span class="line">    <span class="meta">@TableId(type = IdType.AUTO)</span></span><br><span class="line">    <span class="comment">// 标记表中的id字段</span></span><br><span class="line">    <span class="meta">@Id</span></span><br><span class="line">    <span class="keyword">private</span> Long id;<span class="comment">//商品id</span></span><br><span class="line">    <span class="comment">// 标记表中与属性名不一致的字段</span></span><br><span class="line">    <span class="meta">@Column(name = &quot;name&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String name;<span class="comment">//商品名称</span></span><br><span class="line">    <span class="keyword">private</span> String title;<span class="comment">//商品标题</span></span><br><span class="line">    <span class="keyword">private</span> Long price;<span class="comment">//价格（分）</span></span><br><span class="line">    <span class="keyword">private</span> String image;<span class="comment">//商品图片</span></span><br><span class="line">    <span class="keyword">private</span> String category;<span class="comment">//分类名称</span></span><br><span class="line">    <span class="keyword">private</span> String brand;<span class="comment">//品牌名称</span></span><br><span class="line">    <span class="keyword">private</span> String spec;<span class="comment">//规格</span></span><br><span class="line">    <span class="keyword">private</span> Integer status;<span class="comment">//商品状态 1-正常，2-下架</span></span><br><span class="line">    <span class="keyword">private</span> Date createTime;<span class="comment">//创建时间</span></span><br><span class="line">    <span class="keyword">private</span> Date updateTime;<span class="comment">//更新时间</span></span><br><span class="line">    <span class="meta">@TableField(exist = false)</span></span><br><span class="line">    <span class="comment">// 标记不属于表中的字段</span></span><br><span class="line">    <span class="meta">@Transient</span></span><br><span class="line">    <span class="keyword">private</span> Integer stock;</span><br><span class="line">    <span class="meta">@TableField(exist = false)</span></span><br><span class="line">    <span class="meta">@Transient</span></span><br><span class="line">    <span class="keyword">private</span> Integer sold;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="5-3-4-编写监听器"><a href="#5-3-4-编写监听器" class="headerlink" title="5.3.4.编写监听器"></a>5.3.4.编写监听器</h3><p>通过实现<code>EntryHandler&lt;T&gt;</code>接口编写监听器，监听Canal消息。注意两点：</p>
<ul>
<li>实现类通过<code>@CanalTable(&quot;tb_item&quot;)</code>指定监听的表信息</li>
<li>EntryHandler的泛型是与表对应的实体类</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.heima.item.canal;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.github.benmanes.caffeine.cache.Cache;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.config.RedisHandler;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.pojo.Item;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"><span class="keyword">import</span> top.javatool.canal.client.annotation.CanalTable;</span><br><span class="line"><span class="keyword">import</span> top.javatool.canal.client.handler.EntryHandler;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 指定要监听的表</span></span><br><span class="line"><span class="meta">@CanalTable(&quot;tb_item&quot;)</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="comment">// 指定表关联的实体类</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ItemHandler</span> <span class="keyword">implements</span> <span class="title class_">EntryHandler</span>&lt;Item&gt; &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RedisHandler redisHandler;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> Cache&lt;Long, Item&gt; itemCache;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 监听到数据库的 增、改、删 的消息</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">insert</span><span class="params">(Item item)</span> &#123;</span><br><span class="line">        <span class="comment">// 写数据到JVM进程缓存</span></span><br><span class="line">        itemCache.put(item.getId(), item);</span><br><span class="line">        <span class="comment">// 写数据到redis</span></span><br><span class="line">        redisHandler.saveItem(item);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">update</span><span class="params">(Item before, Item after)</span> &#123;</span><br><span class="line">        <span class="comment">// 写数据到JVM进程缓存</span></span><br><span class="line">        itemCache.put(after.getId(), after);</span><br><span class="line">        <span class="comment">// 写数据到redis</span></span><br><span class="line">        redisHandler.saveItem(after);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">delete</span><span class="params">(Item item)</span> &#123;</span><br><span class="line">        <span class="comment">// 删除数据到JVM进程缓存</span></span><br><span class="line">        itemCache.invalidate(item.getId());</span><br><span class="line">        <span class="comment">// 删除数据到redis</span></span><br><span class="line">        redisHandler.deleteItemById(item.getId());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>在这里对Redis的操作都封装到了RedisHandler这个对象中，是我们之前做缓存预热时编写的一个类，内容如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.heima.item.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.core.JsonProcessingException;</span><br><span class="line"><span class="keyword">import</span> com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.pojo.Item;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.pojo.ItemStock;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.service.IItemService;</span><br><span class="line"><span class="keyword">import</span> com.heima.item.service.IItemStockService;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.InitializingBean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.StringRedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RedisHandler</span> <span class="keyword">implements</span> <span class="title class_">InitializingBean</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> StringRedisTemplate redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> IItemService itemService;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> IItemStockService stockService;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">ObjectMapper</span> <span class="variable">MAPPER</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 初始化缓存</span></span><br><span class="line">        <span class="comment">// 1.查询商品信息</span></span><br><span class="line">        List&lt;Item&gt; itemList = itemService.list();</span><br><span class="line">        <span class="comment">// 2.放入缓存</span></span><br><span class="line">        <span class="keyword">for</span> (Item item : itemList) &#123;</span><br><span class="line">            <span class="comment">// 2.1.item序列化为JSON</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> MAPPER.writeValueAsString(item);</span><br><span class="line">            <span class="comment">// 2.2.存入redis</span></span><br><span class="line">            redisTemplate.opsForValue().set(<span class="string">&quot;item:id:&quot;</span> + item.getId(), json);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 3.查询商品库存信息</span></span><br><span class="line">        List&lt;ItemStock&gt; stockList = stockService.list();</span><br><span class="line">        <span class="comment">// 4.放入缓存</span></span><br><span class="line">        <span class="keyword">for</span> (ItemStock stock : stockList) &#123;</span><br><span class="line">            <span class="comment">// 2.1.item序列化为JSON</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> MAPPER.writeValueAsString(stock);</span><br><span class="line">            <span class="comment">// 2.2.存入redis</span></span><br><span class="line">            redisTemplate.opsForValue().set(<span class="string">&quot;item:stock:id:&quot;</span> + stock.getId(), json);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">saveItem</span><span class="params">(Item item)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> MAPPER.writeValueAsString(item);</span><br><span class="line">            redisTemplate.opsForValue().set(<span class="string">&quot;item:id:&quot;</span> + item.getId(), json);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (JsonProcessingException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">deleteItemById</span><span class="params">(Long id)</span> &#123;</span><br><span class="line">        redisTemplate.delete(<span class="string">&quot;item:id:&quot;</span> + id);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/xlrblog/tags/SpringCloud/" rel="tag"># SpringCloud</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/xlrblog/2023/11/04/%E5%88%86%E5%B8%83%E5%BC%8F%E7%BC%93%E5%AD%98/" rel="prev" title="分布式缓存">
      <i class="fa fa-chevron-left"></i> 分布式缓存
    </a></div>
      <div class="post-nav-item"></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AF%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="nav-number">1.</span> <span class="nav-text">1.什么是多级缓存</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-JVM%E8%BF%9B%E7%A8%8B%E7%BC%93%E5%AD%98"><span class="nav-number">2.</span> <span class="nav-text">2.JVM进程缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-%E5%AF%BC%E5%85%A5%E6%A1%88%E4%BE%8B"><span class="nav-number">2.1.</span> <span class="nav-text">2.1.导入案例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-%E5%88%9D%E8%AF%86Caffeine"><span class="nav-number">2.2.</span> <span class="nav-text">2.2.初识Caffeine</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-%E5%AE%9E%E7%8E%B0JVM%E8%BF%9B%E7%A8%8B%E7%BC%93%E5%AD%98"><span class="nav-number">2.3.</span> <span class="nav-text">2.3.实现JVM进程缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-1-%E9%9C%80%E6%B1%82"><span class="nav-number">2.3.1.</span> <span class="nav-text">2.3.1.需求</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-2-%E5%AE%9E%E7%8E%B0"><span class="nav-number">2.3.2.</span> <span class="nav-text">2.3.2.实现</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-Lua%E8%AF%AD%E6%B3%95%E5%85%A5%E9%97%A8"><span class="nav-number">3.</span> <span class="nav-text">3.Lua语法入门</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-%E5%88%9D%E8%AF%86Lua"><span class="nav-number">3.1.</span> <span class="nav-text">3.1.初识Lua</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-HelloWorld"><span class="nav-number">3.2.</span> <span class="nav-text">3.1.HelloWorld</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-%E5%8F%98%E9%87%8F%E5%92%8C%E5%BE%AA%E7%8E%AF"><span class="nav-number">3.3.</span> <span class="nav-text">3.2.变量和循环</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-1-Lua%E7%9A%84%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B"><span class="nav-number">3.3.1.</span> <span class="nav-text">3.2.1.Lua的数据类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-2-%E5%A3%B0%E6%98%8E%E5%8F%98%E9%87%8F"><span class="nav-number">3.3.2.</span> <span class="nav-text">3.2.2.声明变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-3-%E5%BE%AA%E7%8E%AF"><span class="nav-number">3.3.3.</span> <span class="nav-text">3.2.3.循环</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-%E6%9D%A1%E4%BB%B6%E6%8E%A7%E5%88%B6%E3%80%81%E5%87%BD%E6%95%B0"><span class="nav-number">3.4.</span> <span class="nav-text">3.3.条件控制、函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-1-%E5%87%BD%E6%95%B0"><span class="nav-number">3.4.1.</span> <span class="nav-text">3.3.1.函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-2-%E6%9D%A1%E4%BB%B6%E6%8E%A7%E5%88%B6"><span class="nav-number">3.4.2.</span> <span class="nav-text">3.3.2.条件控制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-3-%E6%A1%88%E4%BE%8B"><span class="nav-number">3.4.3.</span> <span class="nav-text">3.3.3.案例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-%E5%AE%9E%E7%8E%B0%E5%A4%9A%E7%BA%A7%E7%BC%93%E5%AD%98"><span class="nav-number">4.</span> <span class="nav-text">4.实现多级缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-%E5%AE%89%E8%A3%85OpenResty"><span class="nav-number">4.1.</span> <span class="nav-text">4.1.安装OpenResty</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E5%AE%89%E8%A3%85"><span class="nav-number">4.1.1.</span> <span class="nav-text">1.安装</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1%EF%BC%89%E5%AE%89%E8%A3%85"><span class="nav-number">4.1.1.1.</span> <span class="nav-text">1）安装</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5%EF%BC%89%E7%9B%AE%E5%BD%95%E7%BB%93%E6%9E%84"><span class="nav-number">4.1.1.2.</span> <span class="nav-text">5）目录结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6%EF%BC%89%E9%85%8D%E7%BD%AEnginx%E7%9A%84%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F"><span class="nav-number">4.1.1.3.</span> <span class="nav-text">6）配置nginx的环境变量</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E5%90%AF%E5%8A%A8%E5%92%8C%E8%BF%90%E8%A1%8C"><span class="nav-number">4.1.2.</span> <span class="nav-text">2.启动和运行</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-%E5%A4%87%E6%B3%A8"><span class="nav-number">4.1.3.</span> <span class="nav-text">3.备注</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-OpenResty%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8"><span class="nav-number">4.2.</span> <span class="nav-text">4.2.OpenResty快速入门</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-1-%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86%E6%B5%81%E7%A8%8B"><span class="nav-number">4.2.1.</span> <span class="nav-text">4.2.1.反向代理流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-2-OpenResty%E7%9B%91%E5%90%AC%E8%AF%B7%E6%B1%82"><span class="nav-number">4.2.2.</span> <span class="nav-text">4.2.2.OpenResty监听请求</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-3-%E7%BC%96%E5%86%99item-lua"><span class="nav-number">4.2.3.</span> <span class="nav-text">4.2.3.编写item.lua</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0%E5%A4%84%E7%90%86"><span class="nav-number">4.3.</span> <span class="nav-text">4.3.请求参数处理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-1-%E8%8E%B7%E5%8F%96%E5%8F%82%E6%95%B0%E7%9A%84API"><span class="nav-number">4.3.1.</span> <span class="nav-text">4.3.1.获取参数的API</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-2-%E8%8E%B7%E5%8F%96%E5%8F%82%E6%95%B0%E5%B9%B6%E8%BF%94%E5%9B%9E"><span class="nav-number">4.3.2.</span> <span class="nav-text">4.3.2.获取参数并返回</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-4-%E6%9F%A5%E8%AF%A2Tomcat"><span class="nav-number">4.4.</span> <span class="nav-text">4.4.查询Tomcat</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-1-%E5%8F%91%E9%80%81http%E8%AF%B7%E6%B1%82%E7%9A%84API"><span class="nav-number">4.4.1.</span> <span class="nav-text">4.4.1.发送http请求的API</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-2-%E5%B0%81%E8%A3%85http%E5%B7%A5%E5%85%B7"><span class="nav-number">4.4.2.</span> <span class="nav-text">4.4.2.封装http工具</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-3-CJSON%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="nav-number">4.4.3.</span> <span class="nav-text">4.4.3.CJSON工具类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-4-%E5%AE%9E%E7%8E%B0Tomcat%E6%9F%A5%E8%AF%A2"><span class="nav-number">4.4.4.</span> <span class="nav-text">4.4.4.实现Tomcat查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-5-%E5%9F%BA%E4%BA%8EID%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1"><span class="nav-number">4.4.5.</span> <span class="nav-text">4.4.5.基于ID负载均衡</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1%EF%BC%89%E5%8E%9F%E7%90%86"><span class="nav-number">4.4.5.1.</span> <span class="nav-text">1）原理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2%EF%BC%89%E5%AE%9E%E7%8E%B0"><span class="nav-number">4.4.5.2.</span> <span class="nav-text">2）实现</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3%EF%BC%89%E6%B5%8B%E8%AF%95"><span class="nav-number">4.4.5.3.</span> <span class="nav-text">3）测试</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-5-Redis%E7%BC%93%E5%AD%98%E9%A2%84%E7%83%AD"><span class="nav-number">4.5.</span> <span class="nav-text">4.5.Redis缓存预热</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-6-%E6%9F%A5%E8%AF%A2Redis%E7%BC%93%E5%AD%98"><span class="nav-number">4.6.</span> <span class="nav-text">4.6.查询Redis缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-6-1-%E5%B0%81%E8%A3%85Redis%E5%B7%A5%E5%85%B7"><span class="nav-number">4.6.1.</span> <span class="nav-text">4.6.1.封装Redis工具</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-6-2-%E5%AE%9E%E7%8E%B0Redis%E6%9F%A5%E8%AF%A2"><span class="nav-number">4.6.2.</span> <span class="nav-text">4.6.2.实现Redis查询</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-7-Nginx%E6%9C%AC%E5%9C%B0%E7%BC%93%E5%AD%98"><span class="nav-number">4.7.</span> <span class="nav-text">4.7.Nginx本地缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-7-1-%E6%9C%AC%E5%9C%B0%E7%BC%93%E5%AD%98API"><span class="nav-number">4.7.1.</span> <span class="nav-text">4.7.1.本地缓存API</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-7-2-%E5%AE%9E%E7%8E%B0%E6%9C%AC%E5%9C%B0%E7%BC%93%E5%AD%98%E6%9F%A5%E8%AF%A2"><span class="nav-number">4.7.2.</span> <span class="nav-text">4.7.2.实现本地缓存查询</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-%E7%BC%93%E5%AD%98%E5%90%8C%E6%AD%A5"><span class="nav-number">5.</span> <span class="nav-text">5.缓存同步</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-%E6%95%B0%E6%8D%AE%E5%90%8C%E6%AD%A5%E7%AD%96%E7%95%A5"><span class="nav-number">5.1.</span> <span class="nav-text">5.1.数据同步策略</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-%E5%AE%89%E8%A3%85Canal"><span class="nav-number">5.2.</span> <span class="nav-text">5.2.安装Canal</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-1-%E8%AE%A4%E8%AF%86Canal"><span class="nav-number">5.2.1.</span> <span class="nav-text">5.2.1.认识Canal</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-2-%E5%AE%89%E8%A3%85Canal"><span class="nav-number">5.2.2.</span> <span class="nav-text">5.2.2.安装Canal</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E5%BC%80%E5%90%AFMySQL%E4%B8%BB%E4%BB%8E"><span class="nav-number">5.2.2.1.</span> <span class="nav-text">1.开启MySQL主从</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-1-%E5%BC%80%E5%90%AFbinlog"><span class="nav-number">5.2.2.1.1.</span> <span class="nav-text">1.1.开启binlog</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-2-%E8%AE%BE%E7%BD%AE%E7%94%A8%E6%88%B7%E6%9D%83%E9%99%90"><span class="nav-number">5.2.2.1.2.</span> <span class="nav-text">1.2.设置用户权限</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E5%AE%89%E8%A3%85Canal"><span class="nav-number">5.2.2.2.</span> <span class="nav-text">2.安装Canal</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-1-%E5%88%9B%E5%BB%BA%E7%BD%91%E7%BB%9C"><span class="nav-number">5.2.2.2.1.</span> <span class="nav-text">2.1.创建网络</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-3-%E5%AE%89%E8%A3%85Canal"><span class="nav-number">5.2.2.2.2.</span> <span class="nav-text">2.3.安装Canal</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-3-%E7%9B%91%E5%90%ACCanal"><span class="nav-number">5.3.</span> <span class="nav-text">5.3.监听Canal</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-1-%E5%BC%95%E5%85%A5%E4%BE%9D%E8%B5%96%EF%BC%9A"><span class="nav-number">5.3.1.</span> <span class="nav-text">5.3.1.引入依赖：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-2-%E7%BC%96%E5%86%99%E9%85%8D%E7%BD%AE%EF%BC%9A"><span class="nav-number">5.3.2.</span> <span class="nav-text">5.3.2.编写配置：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-3-%E4%BF%AE%E6%94%B9Item%E5%AE%9E%E4%BD%93%E7%B1%BB"><span class="nav-number">5.3.3.</span> <span class="nav-text">5.3.3.修改Item实体类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-4-%E7%BC%96%E5%86%99%E7%9B%91%E5%90%AC%E5%99%A8"><span class="nav-number">5.3.4.</span> <span class="nav-text">5.3.4.编写监听器</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="君不见"
      src="/xlrblog/images/avatar.gif">
  <p class="site-author-name" itemprop="name">君不见</p>
  <div class="site-description" itemprop="description">君不见，黄河之水天上来，奔流到海不复回。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/xlrblog/archives/">
        
          <span class="site-state-item-count">50</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">25</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/decxlr" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;decxlr" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">君不见</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/xlrblog/lib/anime.min.js"></script>
  <script src="/xlrblog/lib/velocity/velocity.min.js"></script>
  <script src="/xlrblog/lib/velocity/velocity.ui.min.js"></script>

<script src="/xlrblog/js/utils.js"></script>

<script src="/xlrblog/js/motion.js"></script>


<script src="/xlrblog/js/schemes/pisces.js"></script>


<script src="/xlrblog/js/next-boot.js"></script>




  




  
<script src="/xlrblog/js/local-search.js"></script>













  

  

</body>
</html>
